Home > Enterprise >  How can we create OBJ property with the same name from array values?
How can we create OBJ property with the same name from array values?

Time:06-26

Hello I'm trying to create an object that includes under the same property name a bunch of array values, This what I'm trying

const quiz = [
    {question: 'Who is the main character of DBZ',
    options: ['Vegetta','Gohan','Goku']}
]

const newObj = {
    options: []
}
quiz.forEach((item)=>{
    item.options.forEach((item, index)=>{
        
    newObj.options[`name${index}`] = item
    })
})

expected value =

 newObj = {
    options: [{name: 'Vegetta'},{name:'Gohan'},{name:'Goku'}]
}

actual value received =

newObj = {
  { options: [ name0: 'Vegetta', name1: 'Gohan', name2: 'Goku' ] }}

Thanks in advance!

CodePudding user response:

As you've noticed, newObj.options[`name${index}`] = item creates a new key on your options array, and sets that to item. You instead want to push an object of the form {name: item} into your array. There are a few ways you could go about this, one way is to use .push() like so:

quiz.forEach((item)=>{
  item.options.forEach((item)=>{
    newObj.options.push({name: item});
  })
});

while not as common, you can also use set the current index of options, which is slightly different to the above example, as it will maintain the same index, which can be important if quiz is a sparse array that you want to keep the same indexing of on options:

quiz.forEach((item)=>{
  item.options.forEach((item, index)=>{
    newObj.options[index] = {name: item};
  })
});

Example of the difference:

const arr = [1, 2,,,5]; // sparse array
const pushRes = [];
const indxRes = [];

arr.forEach(n => pushRes.push(n));
arr.forEach((n, i) => indxRes[i] = n);
console.log("Push result", pushRes);
console.log("Index result", indxRes);


For a different approach, you also have the option of using something like .flatMap() and .map() to create your options array, which you can use to create newObj:

const quiz = [
  {question: 'Who is the main character of DBZ',
    options: ['Vegetta','Gohan','Goku']}
];

const options = quiz.flatMap(({options}) => options.map(name => ({name})));
const newObj = {options};
console.log(newObj);

  • Related