简体   繁体   中英

Array of objects to object with keys JSON

This is the data recived from an API Call

[
    {
        "id": "id1",
        "data": "text"
    },
    {
        "id": "id2",
        "data": "text"
    }
]

How could i get the JSON data to look like this?

{
    "id1": {
        "data": "text"
    },
    "id2": {
        "data": "text"
    }
}

You can use array#reduce

 var data = [ { "id": "id1", "data": "text" }, { "id": "id2", "data": "text" } ], result = data.reduce((r,{id,data}) => (r[id] = {data}, r), {}); console.log(result); 

You could use Object.assign a and spread syntax ... b with Array#map c for the new properties with destructuring assignment d , computed property names e and short hand properties f .

Object.assign(...array.map(({ id, data }) => ({ [id]: { data } })))
aaaaaaaaaaaaa bbbccccccccc  dddddddddddd        eeee    ffff

 var array = [{ id: "id1", data: "text" }, { id: "id2", data: "text" }], object = Object.assign(...array.map(({ id, data }) => ({ [id]: { data } }))); console.log(object); 

use lodash groupBy

var a = [
        {
            "id": "id1",
            "data": "text"
        },
        {
            "id": "id2",
            "data": "text"
        }
    ]
_.groupBy(a, 'id')

result

{
    "id1": {
        "data": "text"
    },
    "id2": {
        "data": "text"
    }
}

or you can use this also

a.reduce((acc, item) => {
   acc[item.id] = item;
   return acc;
}, {})

Use any of the two, which ever you find simpler.

 var arr = [ { "id": "id1", "data": "text" }, { "id": "id2", "data": "text" } ]; var obj = {}; arr.forEach(o => { obj[o.id] = { data: o.data } }) console.log(obj); 

 var arr = [ { "id": "id1", "data": "text" }, { "id": "id2", "data": "text" } ]; var obj = {}; for (const item of arr) { obj[item.id] = { data: item.data } } console.log(obj); 

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