1

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:''}
}

2 Answers 2

4

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.