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

Rearranging and Matching Array Elements

I am trying to simplify an array with Javascript

[{
{name: orange,
quanity: 1},
{name: apple,
quanity: 3}
}]

I want

[{
orange:1,
apple: 3
}]

I have tried

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

const keys = flat.map(item => {
            item.name = item.quanity
        })

But I get

[ undefined, undefined ]

Thanks!

>Solution :

You can return the key-value pairs you want in the final object from the map callback, then use Object.fromEntries to create the combined object.

let arr=[{name:"orange",quanity:1},{name:"apple",quanity:3}];
let res = [Object.fromEntries(arr.map(o => [o.name, o.quanity]))];
console.log(res);
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