I want to convert object1 to object2 dynamically because keys like apple and water and inside objects are not static.
const object1 = {
apple:[
{a:''},
{b:''}
],
water:[
{c:''},
{d:''}
]
}
convert to this form:
object2 = {
apple:{a:'',b:''},
water:{c:'',d:''}
}
CodePudding user response:
Use Object.entries
to iterate the key value pairs, then use Object.assign
to merge the inner objects, and finally collect the generated pairs back into one object with Object.fromEntries
:
const object1 = {apple:[{a:''},{b:''}],water:[{c:''},{d:''}]}
const object2 = Object.fromEntries(
Object.entries(object1).map(([key, arr]) =>
[key, Object.assign({}, ...arr)]
)
);
console.log(object2);
CodePudding user response:
const object1 = {
apple:[
{a:''},
{b:''}
],
water:[
{c:''},
{d:''}
]
}
let object={}
Object.keys(object1).forEach((item)=>{
let obj={};
object1[item].map((e)=>{
obj={...obj,...e};
});
object[item]=obj;
})
console.log(object)