Reputation: 13
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.
Upvotes: 1
Views: 102
Reputation: 97
try this way.
let items = {
"item1":{
"key":"Value",
"key":"Value"
},
"item2":{
"key":"Value",
"key":"Value"
},
"item3":{
"key":"Value",
"key":"Value",
"subItem3":{
"key":"Value",
"key":"Value"
}
}
}
items.item2.item3 = items.item3
delete items.item3
console.log(items)
Upvotes: 0
Reputation: 31145
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 }
Upvotes: 2
Reputation: 763
Let's say it's in a variable myObject.
myObject.item2.item3 = myObject.item3;
delete myObject.item3;
Upvotes: 0