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

223
Views
JS creating multi value objects array from an array

Trying to get this ['Team Instinct', 'Team Valor', 'Team Mystic']

To this

[{
    answer: "Team Instinct",
    id: asdfsodijha120-938a //nanoid()
 },
 {
    answer: "Team Valor",
    id: 12390i1-293-12093a2 //nanoid()
 },
 {
    answer: "Team Mystic",
    id: 123908320i09i09ss8a //nanoid()
 }
]

What i tried so far

const { nanoid } = require("nanoid")

const array = ['Team Instinct', 'Team Valor', 'Team Mystic']
let object = {}

obcject = array.reduce((prevValue,currentValue) => {
    prevValue.push({
        answer: currentValue,
        id: nanoid()
    })
},[])

ERROR I GET TypeError: Cannot read properties of undefined (reading 'push')

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

0

You forgot to return prevValue;

 const { nanoid } = require("nanoid")
    
    const array = ['Team Instinct', 'Team Valor', 'Team Mystic']
    let object = {}
    
    obcject = array.reduce((prevValue,currentValue) => {
        prevValue.push({
            answer: currentValue,
            id: nanoid()
        })
        return prevValue
    
    },[])
about 4 years ago · Juan Pablo Isaza Report

0

Orig answer is correct, you're missing the return. However, here's an alternate way of writing it

const { nanoid } = require("nanoid")
let object = ['Team Instinct', 'Team Valor', 'Team Mystic'].reduce((prevValue, currentValue) => ([...prevValue, {
  answer: currentValue,
  id: nanoid()
}]), [])

about 4 years ago · Juan Pablo Isaza Report

0

When you use a reducer You lust return the value after pushing in it.

So first error, you never return the result in the callback function. The seconde one, is that you trying then to assign the result of the reduce (an array) to an object.

const { nanoid } = require("nanoid");

const array = ['Team Instinct', 'Team Valor', 'Team Mystic'];

const result = array.reduce((prevValue,currentValue) => {
    prevValue.push({
        answer: currentValue,
        id: nanoid()
    });
    return prevValue;
},[]);
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!