'How can I simplify a nested object which has a lot of repetitions?
All these three objects have the exact same property and values. Is there any way to simplify the code and make it shorter?
const MyMap = {
'myObject': {
propone: 'One',
proptwo: 'Two',
propthree: 'Three'
},
'yourObject': {
propone: 'One',
proptwo: 'Two',
propthree: 'Three'
},
'hisObject': {
propone: 'One',
proptwo: 'Two',
propthree: 'Three'
}
};
Solution 1:[1]
You can store the object in its own variable and spread it into MyMap:
const innerObject = {
propone: 'One',
proptwo: 'Two',
propthree: 'Three',
};
const MyMap = {
myObject: { ...innerObject },
yourObject: { ...innerObject },
hisObject: { ...innerObject }
};
console.log(MyMap);
.as-console-wrapper {
max-height: 100% !important;
top: auto;
}
Or for something which allows greater flexibility in the variable names:
const innerObject = {
propone: 'One',
proptwo: 'Two',
propthree: 'Three',
};
const propNames = ['myObject', 'yourObject', 'hisObject'];
let MyMap = propNames.reduce((a, c) => {
a[c] = { ...innerObject };
return a;
}, {});
console.log(MyMap);
.as-console-wrapper {
max-height: 100% !important;
top: auto;
}
With even more simplicity as suggested by Matt Morgan:
const MyMap = propNames.reduce((a, c) => ({...a, [c]: {...innerObject}}), {});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
