Learning
Learning

Reputation: 786

Create an Dynamic Array Object with key value pairs

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 ?

Upvotes: 0

Views: 194

Answers (3)

Mohamed-Dhia
Mohamed-Dhia

Reputation: 1

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,
    ])
  )
);

Upvotes: 0

secan
secan

Reputation: 2659

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

Upvotes: 0

Shubham Khatri
Shubham Khatri

Reputation: 281626

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

Upvotes: 1

Related Questions