Issue
I am struggling to push one object into another. I have a multidimensional JSON object like
{
"item1":{
"key":"Value",
"key":"Value"
},
"item2":{
"key":"Value",
"key":"Value"
},
"item3":{
"key":"Value",
"key":"Value",
"subItem3":{
"key":"Value",
"key":"Value"
}
}
}
I want to push item3 in item2 like
{
"item1":{
"key":"Value",
"key":"Value"
},
"item2":{
"key":"Value",
"key":"Value",
"item3":{
"key":"Value",
"key":"Value",
"subItem3":{
"key":"Value",
"key":"Value"
}
}
}
}
How to achieve that any help will be appreciated.
Solution
The question is vague at the moment. And the given input object is wrong. An object cannot have duplicate properties. Adjusting for these errors, you could probably use Object.entries()
to get an iterable array of the object and use Array#reduce
on it to transform it to the required form
Try the following
const input = {
"item1": {
"key1": "Value1",
"key2": "Value2"
},
"item2": {
"key1": "Value1",
"key2": "Value2"
},
"item3": {
"key1": "Value1",
"key2": "Value2",
"subItem3": {
"key1": "Value1",
"key2": "Value2"
}
}
};
const output = Object.entries(input).reduce((acc, [key, value]) => {
if (key === 'item3')
acc['item2'] = { ...acc['item2'], [key]: value };
else
acc[key] = value;
return acc;
}, Object.create(null));
console.log(output);
.as-console-wrapper { max-height: 100% !important; top: 0px }