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