1

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 ]..

2
  • Because the callback of the unnecessary .flatMap() call doesn't return anything Commented Sep 21, 2020 at 11:02
  • 1
    .return ... in a .forEach() callback doesn't do anything. Commented Sep 21, 2020 at 11:03

2 Answers 2

2

You could get the entries and map new properties.

const
    fixed = { pear: 100, apple: 4 },
    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 }],
    dataset = arr.map(d => ({ ...d, ...Object.fromEntries(Object
      .entries(fixed)
      .map(([k, v]) => [k, v - d[k]])
  ) }));

console.log(dataset);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

Comments

0

If the fixed object has to be a fixed object with same fields, then you can try this

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

        let data = arr.map((item) => {
            return { ...item, pear: fixed.pear - item.pear,     apple: fixed.apple - item.apple };
        });
        console.log('checkk', data);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.