Lets say I have an Array of Objects and each have an Array of objects inside them.
let nestedObjects = [{
name: '1',
values: [{id: 1}]
},
{
name: '2',
values: [{id: 2}]
}]
Now, I want to do something with each Object's values id. Sort of like this
let nestedObjects = [{
name: '1',
values: [{
id: 1
}]
},
{
name: '2',
values: [{
id: 2
}]
}
];
let someArray = [];
nestedObjects.forEach(obj => {
obj.values.forEach(value => {
someArray.push(value.id * 2);
});
});
console.log('Values', someArray);
I can sort of change this to use a reduce and possibly a map inside the reduce, but it still feels clunky and not really "functionally". Is there a different way to write it to make it shorter and easier to read?
I would like to get to something like:
let someArray = nestedObjects.map(obj => obj.values)
.map(value => value.id * 2)
console.log('VALUES', someArray);
Note: It is not really about the above code, but more about the FP way of thinking/coding.
nestedObjects.reduce((p, o) => p.concat(o.values.map(v => v.id * 2)), [])looks tidy enough.reduceinside amap, because the latter have to return the same context, that is anArrayin your example:nestedObjects.map(o => o.values.reduce((acc, p) => acc + p.id * 2, 0)).