Home > Net >  How to add elements in an object while traversing through an array using map?
How to add elements in an object while traversing through an array using map?

Time:11-22

I am having an array like this : arr = [ {id:0,name:Mark} , {id:1,name:Ron}, {id:2,name:Henry}, {id:3,name:Rose}].

I want to create an object like this :

obj1 = { Mark:false, Ron:false, Henry:false, Rose:flase }

I am using map to traverse through the array like this

let obj1 = {};
obj1 = arr.map((item)=> {
    obj1[item.name] = false;
  })

How can I achieve the following result?

CodePudding user response:

You could map entries and build an object from the pairs.

const
    data = [{ id: 0, name: 'Mark' }, { id: 1, name: 'Ron' }, { id: 2, name: 'Henry' }, { id: 3, name: 'Rose' }],
    result = Object.fromEntries(data.map(({ name }) => [name, false]));
    
console.log(result);

CodePudding user response:

Object.fromEntries() is probably the best idea. But you could also use reduce, if you got more operations on the array and want to stick to the "pipe" approach.

const arr = [
  { id: 0, name: 'Mark' },
  { id: 1, name: 'Ron' },
  { id: 2, name: 'Henry' },
  { id: 3, name: 'Rose' }
];

const objA = arr
  .reduce((previous, { name }) => ({ ...previous, [name]: false }), {});

const objB = arr
  .reduce((previous, { name }) => {
    previous[name] = false;
    return previous;
  }, {});

The spreach operation {...obj} for objA does effectivly copy the object on each extension, which might not be desirable. But the modern JavaScript engines simplify those expressions anyways.

objB is the more standard approach for me. One additional benefit, in regards to Object.fromEntries() is that you can have some form of standard or default object / settings, which you can use as the start of the reduce (the second parameter) and evaluate in the collection function.

All three options are valid and depend on your code style.

  • Related