Suppose I have:
const fixed = {pear: 100, apple: 4}
const arr = [
{name: 'P1', pear: 150, apple: 2},
{name: 'P2', pear: 50, apple: 5},
{name: 'P3', pear: 450, apple: 1},
{name: 'P4', pear: 100, apple: 3},
]
and I want to have:
const result = [
{name: 'P1', pear: -50, apple: 2},
{name: 'P2', pear: 50, apple: -1},
{name: 'P3', pear: -350, apple: 3},
{name: 'P4', pear: 0, apple: 1},
]
So result has the same items of arr but with edited apple and pear values based on fixed object values.
The new pear (and apple) value should be fixed.pear - oldPearValue, so for example, for arr[0]:
fixed.pear - arr[0].pear = 100 - 150 = -50 --> result[0].pear = -50
Here is what I tried:
function difference(fixed, value) {
return value - fixed
}
const fixed = {pear: 100, apple: 4}
const arr = [
{name: 'P1', pear: 150, apple: 2},
{name: 'P2', pear: 50, apple: 5},
{name: 'P3', pear: 450, apple: 1},
{name: 'P4', pear: 100, apple: 3},
]
const dataset = arr.flatMap((d) => {
Object.entries(fixed).forEach(([key, value]) => {
return { ...d, [key]: difference(value, d[key]) }
})
})
console.log(dataset)
as you can see, the result is [ undefined, undefined, undefined, undefined ]..
.flatMap()call doesn't return anything.return ...in a.forEach()callback doesn't do anything.