Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

123
Views
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 =

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

Thanks in advance!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!