簡體   English   中英

使用鍵值對創建動態數組 Object

[英]Create an Dynamic Array Object with key value pairs

我需要從現有的 object 創建一個動態鍵值對

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

這里的邏輯是創建一個新數組 object 並從reqCost中減去amfqtyCost

我寫的邏輯

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

這返回 139 和 159 分別是 (1555 - 1416 = 139) 和 (1575 1416 = 159)

預期 output:

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

我該如何合並?

您只需從 map function 中返回更新的 object。 同樣對於外部迭代,使用 map 而不是 forEach 來返回最終結果

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

你可以這樣做:

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

您可以反轉Object.entries

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

使用Object.fromEntries進行轉換

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

代碼看起來像這樣

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM