1

I have an array declared which uses the Object.assign:

var obj = [{
  id: 1,
  value: 'abc'
}, {
  id: 2,
  value: 'xyz'
}];

console.log(Object.assign({}, obj));

it's getting transformed as,

{ 
    '0': { id: 1, value: 'abc' }, 
    '1': { id: 2, value: 'xyz' } 
}

However I need to have this as, (here the 1 and 2 represents the id attribute of my object)

{
        '1': {id: 1, value: 'abc'},
        '2': {id: 2, value: 'xyz'}
}

I've tried few, but had no luck, Can someone shed some light?

1
  • Why do you need it to be one and not zero? The first key in an ordinal array is typically going to be 0. Commented Apr 24, 2018 at 14:30

4 Answers 4

6

You could map the objects in an object with the wanted key and assign it to a single object.

var objects = [{ id: 1, value: 'abc' }, { id: 2, value: 'xyz' }],
    result = Object.assign(...objects.map(o => ({ [o.id]: o })));
    
console.log(result);

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

Comments

4

You can use reduce() method with Object.assign.

var obj = [{id: 1, value: 'abc'}, {id: 2, value: 'xyz'}];
var result = obj.reduce((r, e) => Object.assign(r, {[e.id]: e}), {});
console.log(result)

Note that we are passing a reference of each object in a array and not creating new objects, but you can change that with object assign on e or you can use spread syntax like so:

Object.assign(r, {[e.id]: {...e}})

Comments

3

You can directly use Array#reduce to do that, and there is no need for Object.assign here:

var obj = [{id: 1, value: 'abc'}, {id: 2, value: 'xyz'}];

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

console.log(result);

Comments

3

If you want to use .id to be the key, you can use reduce and use Object.assign

let obj = [{id: 1,value: 'abc'}, {id: 2,value: 'xyz'}];

let result = obj.reduce((c, v) => Object.assign(c, {[v.id]: v}), {});

console.log(result);

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.