Reputation: 339
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
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
Reputation: 386600
You could use Object.assign
a and spread syntax ...
b with Array#map
c 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
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
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