简体   繁体   中英

Convert a map to an array - Javascript

I have a map of objects which I want to convert to an array of objects.

The map looks as follows, using each objects id as a key:

{
    'a' : {
        id ' a',
        name : 'Andrew'
    },
    'b' : {
        id : 'b',
        name : 'Barry'
    },
    'c' : {
        id: 'c',
        name: 'Caroline'
    }
}

and I would like to convert it an an array:

[
    {
        id: 'a',
        name : 'Andrew'
    },{
        id: 'b',
        name : 'Barry'
    },{
        id : 'c',
        name: 'Caroline'
    }
]

preferably using vanilla js, but I use lodash in my application so I have access to that library.

Could someone point me in the right direction please?

Use Object.values() :

 const data = { a: { id: 'a', name: 'Andrew' }, b: { id: 'b', name: 'Barry' }, c: { id: 'c', name: 'Caroline' } }; const result = Object.values(data); console.log(result);

You can do it like this

 const input = { 'a' : { id: ' a', name : 'Andrew' }, 'b' : { id : 'b', name : 'Barry' }, 'c' : { id: 'c', name: 'Caroline' } }; const output = Object.values(input); console.log(output);

You can use Object.entries() and .map() combination for example:

 const data = { 'a' : { id: 'a', name : 'Andrew' }, 'b' : { id : 'b', name : 'Barry' }, 'c' : { id: 'c', name: 'Caroline' } }; const result = Object.entries(data).map(e => e[1]); console.log(result);

Or you can use Object.values() for shorter version.

I hope this helps!

You can simply do it by map through the Object.keys()

 const data = { 'a': { id: ' a', name : 'Andrew' }, 'b': { id : 'b', name : 'Barry' }, 'c': { id: 'c', name: 'Caroline' } }; const arr = Object.keys(data).map(v => data[v]); console.log(arr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM