簡體   English   中英

在 es6 中解析 object 時,如果值存在於 object 中,則存儲變量

[英]store a variable if a value exits in an object when parsing the object in es6

我有一個 object,如下所示:

{
"_attrib": {
    "PieChart": "T",
    "ProductSettings": "true"
},
"WATER": {
    "_attrib": {
        "Step": "5",
        "ProgressAdjust": "41",
    }
},
"TEMP": {
    "_attrib": {
        "Argument": "F7",
        "Default": "00"
    },
    "ITEM": [
        {
            "_attrib": {
                "Name": "Low",
            }
        },
        {
            "_attrib": {
                "Name": "Normal",
            }
        },
        {
            "_attrib": {
                "Name": "High",
            }
        }
    ]
  }
}

我需要解析的是找到 ProgressAdjust 的設置位置,然后在這種情況下將名稱添加到數組中,

我有以下代碼,但是該數組具有所有名稱(即:_attrib、water、temp)。

export const productCustomizationOptions = (product: any) => {
  const options = [];
  Object.entries(product.product).forEach((item1, index1) => {
    Object.values(item1[1]).forEach((item2) => {
      if (item2.ProgressAdjust !== 'undefined') {
        options.push(item1[0]);
      }
    });
 });
 console.log('customization options: ', options);
};

任何幫助,將不勝感激。

  • 使用Object.entries將 object 轉換為鍵/值對數組
  • 使用Array#filter可選鏈接 (?.)過濾此數組

可選的鏈接運算符 (?.) 使您能夠讀取位於連接對象鏈深處的屬性值,而無需檢查鏈中的每個引用是否有效。

  • 最后使用Array#map僅提取鍵

 const obj = {_attrib:{PieChart:"T",ProductSettings:"true"},WATER:{_attrib:{Step:"5",ProgressAdjust:"41"}},TEMP:{_attrib:{Argument:"F7",Default:"00"},ITEM:[{_attrib:{Name:"Low"}},{_attrib:{Name:"Normal"}},{_attrib:{Name:"High"}}]}}, res = Object.entries(obj).filter(([, o]) => o?._attrib?.ProgressAdjust).map(([k]) => k) console.log(res)

暫無
暫無

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

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