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

134
Views
Javascript dynamic function to turn array into object

I am looking to turn an array that looks like this

['group1/ Child 1', 'group1/ Child 2']

into an object dynamically that looks like this

{
     "attributes": {
          "group0": "group1/ Child 1"
          "group1": "group1/ Child 2"
     }
}

the function should allow the array to be

['group1/ Child 1', 'group1/ Child 2', 'group1/ Child 3']

and return ... and etc

{
     "attributes": {
          "group0": "group1/ Child 1"
          "group1": "group1/ Child 2"
          "group2": "group1/ Child 3"
     }
}

I think I should be using a reduce function to achieve this, but haven't been able to get it right yet.

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

0

Yes you can use reduce

const data = ['group1/ Child 1', 'group1/ Child 2', 'group1/ Child 3']
const grouped = data.reduce((acc,item,i) => {
   acc.attributes[`group${i}`]  = item;
   return acc
},{attributes:{}})
console.log(grouped)

But why not just keep the array?

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!