I’d like to learn how to convert a nested object into a new one by rearranging this structure:
JavaScript
x
12
12
1
data =
2
{
3
centeredSlides: {
4
0: true,
5
1300: false
6
},
7
somethingElse: {
8
0: false,
9
1500: 'aString'
10
}
11
}
12
So that it follows this structure:
JavaScript
1
14
14
1
newData =
2
{
3
0: {
4
centeredSlides: true,
5
somethingElse: false
6
},
7
1300: {
8
centeredSlides: false
9
},
10
1500: {
11
somethingElse: 'aString'
12
}
13
}
14
Thanks
Advertisement
Answer
You can grab the entires of your object and use .reduce()
to build a new object from the [[key, value], ...]
entry array. For each [key, value]
you can iterate over the entries of the nested object and use the keys from that as your outer keys of your accumulated/new object:
JavaScript
1
11
11
1
const data = { centeredSlides: { 0: true, 1300: false }, somethingElse: { 0: false, 1500: 'aString' } };
2
3
const res = Object.entries(data).reduce((acc, [innerKey, obj]) => {
4
Object.entries(obj).forEach(([outerKey, val]) => {
5
acc[outerKey] = acc[outerKey] || {}; // grab the object already stored at the `outerKey` or create a new one.
6
acc[outerKey][innerKey] = val;
7
})
8
return acc;
9
}, {});
10
11
console.log(res);