简体   繁体   中英

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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM