1

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

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.