2

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!

1
  • 1
    newObj.options.push({name: item}) instead of ` newObj.options[name${index}] = item` Commented Jun 26, 2022 at 4:30

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

1 Comment

That worked perfectly man Thank you so much! you also gave a good explanation, Have a good one!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.