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:''}
}
>Solution :
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);