Home > Software design >  How to create object fields dynamically based on values in Javascript?
How to create object fields dynamically based on values in Javascript?

Time:09-23

I have an object array like this:

const values = [{name: 'name1', index: 1}, {name: 'name2', index: 2}, {name: 'name3', index: 3}]

Is it possible to create such an object dynamically?

const result = {
  name1: 1,
  name2: 2,
  name3: 3
}

CodePudding user response:

what you can do is the following!

const values = [{name: 'name1', index: 1}, {name: 'name2', index: 2}, {name: 'name3', index: 3}];
const result = {};
values.forEach(value => result[value.name] = value.index);

console.log(result); // {name1: 1, name2: 2, name3: 3}
  • Related