Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 =

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Thanks in advance!

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading