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

119
Views
assign incremental index to nested array of object?

How to assign incremental index to nested array of object below? each members will have a property 1,2,3,4

groupMembersByTitle = [{
    members: [{
        id: 'uuid'
    }, {
        id: 'uuid'
    }]
}, {
    members: [{
        id: 'uuid'
    }, {
        id: 'uuid'
    }]
}]

I'm stuck here

const r = groupMembersByTitle.map(o => ({
    ...o,
    members: o.members.map((o2, index) => ({
        ...o2,
        no: ++index
    }))
}))
about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

You'll need a more persistent outer variable.

const groupMembersByTitle = [{
    members: [{
        id: 'uuid'
    }, {
        id: 'uuid'
    }]
}, {
    members: [{
        id: 'uuid'
    }, {
        id: 'uuid'
    }]
}];

let no = 1;
const mapped = groupMembersByTitle.map(
  obj => ({
    members: obj.members.map(
      member => ({ ...member, no: no++ })
    )
  })
);
console.log(mapped);

about 4 years ago · Santiago Trujillo Report

0

You can use the map parameter thisArg.

map(function(element, index, array) { /* … */ }, thisArg)

const groupMembersByTitle = [{
  members: [{ id: 'uuid' }, { id: 'uuid' }]
}, {
  members: [{ id: 'uuid' }, { id: 'uuid' }]
}];

const r = groupMembersByTitle.map(function(o1) {
  return ({
    members: o1.members.map(
      o2 => ({
        ...o2,
        no: ++this.acc
      })
    )
  });
}, { acc: 0 });

console.log(r);

about 4 years ago · Santiago Trujillo Report

0

You can do it using Array.prototype.map twice and use the indices of the arrays to calculate the no.

const 
  data = [
    { members: [{ id: "uuid" }, { id: "uuid" }] },
    { members: [{ id: "uuid" }, { id: "uuid" }] },
  ],
  result = data.map(({ members }, i) =>
    members.map((m, j) => ({
      ...m,
      no: i * (i ? data[i - 1].members.length : 1) + j + 1,
    }))
  );

console.log(result);

about 4 years ago · Santiago Trujillo 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!