Home > Software engineering >  Convert an array of objects to an object based on its values JavaScript
Convert an array of objects to an object based on its values JavaScript

Time:10-16

I have an array of objects like this:

const array = [{id: 'id1', name: 'name1'}, {id: 'id2', name: 'name2'}, {id: 'id3', name: 'name'}]

I need to get an object whose keys are id values like this:

    const obj = {
      id1: {id: 'id1', name: 'name1'}, 
      id2: {id: 'id2', name: 'name2'},
      id3: {id: 'id3', name: 'name3'}
    }

CodePudding user response:

You can use Object.assign for that.

Example:

const array = [{id: 'id1', name: 'name1'}, {id: 'id2', name: 'name2'}, {id: 'id3', name: 'name'}]

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

console.log(obj);

The above code will output something like {0: {...}, 1: {...}, 2: {...}}. I think it will be better than id1, id2, ..., etc.

CodePudding user response:

You could build a new object with key/value pairs.

const
    data = [{ id: 'id1', name: 'name1' }, { id: 'id2', name: 'name2' }, { id: 'id3', name: 'name' }],
    result = Object.fromEntries(data.map(o => [o.id, o]));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

  • Related