0

I need to create an Dynamic key value pairs from the existing object

const balanceScheule = 1255;
const reqCost = [{Labour Cost: "1555"}, {Material Cost: "1575"}]; // key is dynamic and keeps on changing
const amfqtyCost = 1416;

Here the logic is to create an new array of object and subtract the amfqtyCost from reqCost

Logic i Have written

reqCost.forEach(element => {
    const adjustedAmount = Object.entries(element).map((m) => {
        let adjustedAmount = parseInt(m[1]) - amfqtyCost;
        return adjustedAmount;
    });
    // console.log(...adjustedAmount)
    });

this return 139 and 159 which is (1555 - 1416 = 139) and (1575 1416 = 159) respectively

Expected output :

[{Labour Cost: "139"}, {Material Cost: "159"}]

How to do i merge ?

1
  • You're looking for Object.fromEntries: Object.fromEntries(Object.entries.map(m => [m[0], m[1] - xxx] .... etc Commented Apr 7, 2021 at 9:10

3 Answers 3

1

You just need to return the updated object from within map function. Also for the outer iteration use map instead of forEach to return the final result

const balanceScheule = 1255;
const reqCost = [{
  'Labour Cost': "1555",
}, {
  'Material Cost': "1575",
}]; // key is dynamic and keeps on changing


const amfqtyCost = 1416;
const updatedData = reqCost.map(element => {
  return Object.assign({}, ...Object.entries(element).map(([key, value]) => {
    let adjustedAmount = parseInt(value) - amfqtyCost;
    return {
      [key]: String(adjustedAmount)
    };
  }));
});

console.log(updatedData);

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

Comments

0

You can do something like this:

const reqCost = [{
  'Labour Cost': "1555"
}, {
  'Material Cost': "1575"
}];
const amfqtyCost = 1416;

const adjustedCost = reqCost.map(cost => ({
  [Object.keys(cost)[0]]: (parseInt(Object.values(cost)[0]) - amfqtyCost).toFixed(0)
}));

console.log(adjustedCost);

// OR, if you prefer to be a bit more verbose:
const adjustedCost2 = reqCost.map(cost => {
  const [key, value] = Object.entries(cost)[0];

  return {
    [key]: (parseInt(value) - amfqtyCost).toFixed(0)
  }
});

console.log(adjustedCost2);

Comments

0

You can reverse the Object.entries

{ key : value } => [ [ key, value ] ]

transformation by using Object.fromEntries

[ [ key, value ] ] => { key : value }

the code will look like this

reqCost.map((obj) =>
  Object.fromEntries(
    Object.entries(obj).map(([key, value]) => [
      key,
      parseInt(value) - amfqtyCost,
    ])
  )
);

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.