0

I want to transform:

[
    {id: 1, name: 'one', desc: 'one'},
    {id: 2, name: 'two', desc: 'two'},
    {id: 3, name: 'three', desc: 'three'}
]

to

{
    1: {id: 1, name: 'one', desc: 'one'},
    2: {id: 2, name: 'two', desc: 'two'},
    3: {id: 3, name: 'three', desc: 'three'}
}

What is the most efficient/performant way to do this? Some options would be:

1) https://github.com/gaearon/normalizr

2) d3.nest()

3) const object = {}; array.forEach(item => { object[item.id] = item });

1
  • You already have an object in that configuration, only it starts at 0 instead of 1. ;-) Commented May 2, 2016 at 21:33

4 Answers 4

1

I like Array.prototype.reduce() solutions. Check this out

var arr = [{id: 1, name: 'one', desc: 'one'}, {id: 2, name: 'two', desc: 'two'}, {id: 3, name: 'three', desc: 'three'}],
    obj = arr.reduce((p,c) => {p[c.id] = c; return p},{});

document.write("<pre>" + JSON.stringify(obj,null,2) + "</pre>");

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

Comments

1

You can also use a simple loop:

var arr = [{id: 1, name: 'one', desc: 'one'}, {id: 2, name: 'two', desc: 'two'}, {id: 3, name: 'three', desc: 'three'}],
    obj = {}
for(var item of arr) obj[item.id] = item;

Usually loops are faster than ES5 array methods because they don't have to call a function at each iteration.

Comments

0

I would say that it is:

const obj = Object.assign( {}, array );

Although, I haven't compared its performance to your options.

1 Comment

That doesn't work, OP wants to assign them by their .id not by their index in the array.
0

try this:

ar = [
    {id: 1, name: 'one', desc: 'one'},
    {id: 2, name: 'two', desc: 'two'},
    {id: 3, name: 'three', desc: 'three'}
]

var result = ar.reduce((ac, x) => {return ac[x.id] = x , ac ;}, {})

document.write( JSON.stringify(result) )

but remember that the keys are strings and you're dealing with an object not array...

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.