簡體   English   中英

如何在不更改原始數組的情況下破壞對象屬性?

[英]How do i destruct object properties without mutating original array?

試圖從數組對象中刪除類似屬性,但無法重新聲明拋出錯誤的作用域變量,我如何使用任何更好的方法從對象中刪除類似屬性,而無需更改原始數組?

main.js

const loggerResponse = transformedResponse.map(({ drugName, mailPrice,retailPrice, ...rest  }) => {
    const { copayEmployer, ...mailPriceRest } = mailPrice;
    const { copayEmployer, ...retailPriceRest } = retailPrice;
    return { ...rest, mailPrice: mailPriceRest , retailPrice: retailPriceRest};
  })

TransformationResponse

[
    {
        "isBrand": true,
        "drugName": "Lipitor",
        "drugStrength": "80 mg",
        "drugForm": "Tablet",
        "mailPrice": {
            "copayEmployer": 0,
            "prop2": "test"
        },
        "retialPrice": {
            "copayEmployer": 0,
            "prop2": "test"
        }

    }, {
        "isBrand": true,
        "drugName": "Metformin",
        "drugStrength": "500 mg",
        "drugForm": "Tablet",
        "mailPrice": {
            "copayEmployer": 50,
            "prop2": "test"
        },
        "retailPrice": {
            "copayEmployer": 0,
            "prop2": "test"
        }
    }

]

預期產量

[
    {
        "isBrand": true,
        "drugStrength": "80 mg",
        "drugForm": "Tablet",
        "mailPrice": {
            "prop2": "test"
        },
        "retialPrice": {
            "prop2": "test"
        }

    }, {
        "isBrand": true,
        "drugStrength": "500 mg",
        "drugForm": "Tablet",
        "mailPrice": {
            "prop2": "test"
        },
        "retailPrice": {
            "prop2": "test"
        }
    }

]

實際上,您的方法很棒,但是您需要進行一些更改,請嘗試克隆對象而不是直接使用它,就像:

const loggerResponse = transformedResponse.map(({ drugName, mailPrice, retailPrice, ...rest  }) => {
  const { copayEmployer, ...mailPriceRest } = mailPrice || {};
  const { copayEmployer: copayEmployerRetail, ...retailPriceRest } = retailPrice || {};
  return { ...rest, mailPrice: { ...mailPriceRest, copayEmployer } , retailPrice: { ...retailPriceRest, copayEmployer: copayEmployerRetail }};
})

它應該可以解決問題。

這個解決方案怎么樣?

const loggerResponse = function transform (originalArray) {
  originalArray.map( element => {
    delete element.drugName;
    delete element.mailPrice.copayEmployer;
    delete element.retialPrice.copayEmployer;
   });

  return originalArray;
}

const expectedArray = loggerResponse(transformedResponse);
console.log(expectedArray);

當然,如果需要,您可以克隆原始陣列。 並且請注意,僅使用slice() ,spread運算符等方法進行克隆將不會對其進行深入克隆,但是您可以使用以下代碼來實現:

const deepClone = JSON.parse(JSON.stringify(transformedResponse));

然后,您可以在克隆的陣列上執行所有操作,而無需觸摸原始陣列。

暫無
暫無

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

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