Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how can i convert array of objects to one object

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading