0

I am creating an object from the array of objects, using the value for one of the keys:

const myArray = [
  {
    uuid: '123',
    name: 'abc'
  },
  {
    uuid: '789',
    name: 'xyz'
  }    
];

const newObj = {};
for (var i = 0; i < myArray.length; i++) {
    newObj[myArray[i].uuid] = myArray[i];
}

console.log('result: ', newObj)

how can I do the same using ecma6 practices?

1
  • You can use forEach on the array (which would have worked in ES5 too). That’s about it for base JavaScript. Commented Mar 12, 2018 at 0:40

3 Answers 3

2

Using the functions reduce, Spread syntax, Computed property names and Arrow functions.

const myArray = [  {    uuid: '123',    name: 'abc'  },  {    uuid: '789',    name: 'xyz'  }    ];

var newObj = myArray.reduce((a, c) => ({...a, [c.uuid]: c}), {});
console.log('result: ', newObj)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Resources

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

Comments

2

You could use Object.assign() with map() and spread syntax ...

const myArray = [{uuid: '123',name: 'abc'},{uuid: '789',name: 'xyz'}];

const newObj = Object.assign({}, ...myArray.map(e => ({[e.uuid]: e})))
console.log(newObj)

Comments

0

The other answers are fancy, but I think the most readable, and simplest answer is the following:

const myArray = [{uuid: '123',name: 'abc'},{uuid: '789',name: 'xyz'}];

const newObj = {}
myArray.forEach(item => newObj[item.uuid] = item)

console.log(newObj)

Yes this was available in version 5, but I think is applicable to the goal of the question.

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.