簡體   English   中英

更改數組中 object 中的值

[英]Changing the values inside an object within an array

我正在嘗試提取數組中 object 內的數組,並且我想編輯提取的數組中對象的值。 看起來這應該很簡單,但我不知道為什么我的 forEach 沒有更新對象。 據我了解 forEach 會改變原始數組,為什么這不起作用?

我的預期結果是:


      [
          {
            "label": "400 mg",
            "value": "400 mg",
          },
          {
             "label": "600 mg",
             "value": "600 mg",
          },
          {
             "label": "800 mg",
             "value": "800 mg",
          }
      ]

 const array1 = [ { "Name": "IBU (oral - tablet)", "Strength": [ { "Strength": "400 mg", "NDC": "55111068201" }, { "Strength": "600 mg", "NDC": "55111068301" }, { "Strength": "800 mg", "NDC": "55111068401" } ] }, ]; let newA = array1.map((item) => item.Strength).flatMap((item) => item) newA.forEach((str) => ({label: str.Strength,value: str.Strength})) console.log(newA)

我假設您正在尋找這個,使用.map not.forEach。

 const result = [ { "Name": "IBU (oral - tablet)", "Strength": [ { "Strength": "400 mg", "NDC": "55111068201" }, { "Strength": "600 mg", "NDC": "55111068301" }, { "Strength": "800 mg", "NDC": "55111068401" } ] } ][0].Strength.map(el => ({ label: el.Strength, value: el.Strength })); console.log(result);

 const array1 = [ { "Name": "IBU (oral - tablet)", "Strength": [ { "Strength": "400 mg", "NDC": "55111068201" }, { "Strength": "600 mg", "NDC": "55111068301" }, { "Strength": "800 mg", "NDC": "55111068401" } ] }, ]; let newA = array1.map((item) => item.Strength).flatMap((item) => item) newA.map((str) => { str.label= str.Strength; str.value = str.Strength; delete str.Strength; delete str.NDC }) console.log(newA)

暫無
暫無

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

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