silversurfer
silversurfer

Reputation: 339

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"
    }
}

Upvotes: 1

Views: 65

Answers (4)

Muhammad Adeel
Muhammad Adeel

Reputation: 2884

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

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386600

You could use Object.assigna and spread syntax ...b with Array#mapc for the new properties with destructuring assignmentd, computed property namese and short hand propertiesf.

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

Upvotes: 2

zabusa
zabusa

Reputation: 2719

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;
}, {})

Upvotes: 0

Hassan Imam
Hassan Imam

Reputation: 22534

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

Upvotes: 4

Related Questions