简体   繁体   English

在 es6 中解析 object 时,如果值存在于 object 中,则存储变量

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

I have an object like the following:我有一个 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",
            }
        }
    ]
  }
}

what I need to parse is to find where ProgressAdjust is set and then add the name in this case WATER into an array,我需要解析的是找到 ProgressAdjust 的设置位置,然后在这种情况下将名称添加到数组中,

I have the following code however the array has all the names (ie: _attrib, water, temp).我有以下代码,但是该数组具有所有名称(即:_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);
};

any help would be appreciated.任何帮助,将不胜感激。

  • Using Object.entries convert the object into an array of key/value pairs使用Object.entries将 object 转换为键/值对数组
  • Filter this array using Array#filter and Optional Chaining (?.)使用Array#filter可选链接 (?.)过滤此数组

The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.可选的链接运算符 (?.) 使您能够读取位于连接对象链深处的属性值,而无需检查链中的每个引用是否有效。

  • Finally using Array#map extract out only the keys最后使用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