在 array.forEach 函数语句中使用 if 语句来选择对象数组中的子对象

Using if statement in array.forEach function statement to choose sub-object in array of objects

我无法让 if 语句在 forEach 数组循环调用的函数内运行。

我有一个包含对象的数组,(有一个对象)

arrofobj = [   
{"thing_id":"1a", "val": 1, "Type": "Switch","ValType":{"0":"Open","1":"Closed"}},  
{"thing_id":"1b", "val": 72, "Type": "Sensor","ValType":{"0":"%"}}]

我想测试 Type 是否是一个开关,以便在数组对象的新字段中写入信息 CatX:
- 如果是,我想使用 val 值来确定要在数组 arrofobj.
的新变量中使用哪个 ValType 元素 - 如果没有,我想使用 arrofobj.ValType.0 值

const getCat = function(){
    if(arrofobj.Type !== 'Switch') 
        arrofobj.ValType'.0' 
    } else {
        arrofobj.ValType.(arrofobj.val)
};

arrofobj.forEach(p => p.CatX = getCat() ); 

我没有让 lint 接受代码,所以无法测试。

1) 您必须使用括号表示法以字符串形式访问属性。

2) 您必须正确关闭 if/else 上的括号。

3) 你必须从 getCat 中 return 一些东西才能分配给 p.CatX

4) 您必须在循环内实际将对象发送到 getCat。

const arrofobj = [   
  {"thing_id":"1a", "val": 1, "Type": "Switch","ValType":{"0":"Open","1":"Closed"}},  
  {"thing_id":"1b", "val": 72, "Type": "Sensor","ValType":{"0":"%"}}
];
const getCat = function( obj ){
    if(obj.Type !== 'Switch') {
        return obj.ValType[ '0' ]
    } else {
        return obj.ValType[ obj.val ];
    }
};

arrofobj.forEach(p => {
  p.CatX = getCat(p);
}); 

console.log( arrofobj );

补充一下 Shilly 的回答:

1) 在 long-运行 中,如果这是您自己创建的数据而不是来自第三方端点的数据,您会发现标准化对象的格式 属性 键名(驼峰式)更易于使用。如果它们的格式相同,它不会给您的代码引入那么多错误。

2) 您可以使用对象 destructuring assignment and a ternary operator 来稍微缩短代码占用空间。

const arrofobj = [
  { id: '1a', val: 1, type: 'Switch', valType: { '0': 'Open', '1': 'Closed' } },
  { id: '1b', val: 72, type: 'Sensor', valType: { '0': '%' } }
];

function getCat(obj) {

  // Deconstruct the properties from obj
  const { type, valType, val } = obj;

  // Use a ternary operator to decide what to return
  return type === 'Switch' ? valType[val] : valType['0'];
}

arrofobj.forEach(obj => {
   obj.catX = getCat(obj);
});

console.log(arrofobj);