例如,我收到一个 JSON 响应:
[
{
'key_1': 'value1A',
'key_2': 'value2A',
'key_3': 'value3A'
},
{
'key_1': 'value1B',
'key_2': 'value2B',
}
]
据观察,数组的第二个元素中未提供 key_3
。这里的 keys
对于数组中的每个对象都是相同的。
比方说,我只对使用响应的 key_2
和 key_3
感兴趣,因此我使用 map
如下
this.serv.getInfo(code) // HTTP GET service
.subscribe(res => {
this.data = res.map(el => { // only use necessary key:value pairs
let _out = { // make an object to return
'new_key_1': el.key_2
'new_key_2': '' // if there is no key_3 then leave it empty
}
if ('key_3' in el) { // if this pair exists then add it..
_out['new_key_2'] = el.key_3
return _out;
}
return _out; // if not return with empty string
});
});
这很有效,因为在这种情况下 JSON 响应很小。但我假设如果 JSON 结构庞大且复杂,if(.. in el)
检查可能会增加很多倍。
在将响应映射到新对象时,哪种运算符最适合在这种情况下进行更动态的检查。甚至有必要在 map
函数中创建一个临时 _opt
对象吗?
最佳答案
你可以使用 el['key_3'] || ''
被称为 Short-circuit evaluation .
演示
let data = [
{
'key_1': 'value1A',
'key_2': 'value2A',
'key_3': 'value3A'
},
{
'key_1': 'value1B',
'key_2': 'value2B',
}
],
arr = data.map((el) => {
return {'key_1': el['key_2'], 'key_2': el['key_3'] || ''};
});
console.log(arr);
但是它不包括 el['key_3']
等于 null
、undefined
、false
的情况, 0
。
如果这是 Not Acceptable ,那么 in
运算符是真正确定对象中的键是否存在的唯一方法。您可以将它与 ternary operator 一起使用从而避免使用临时对象——参见演示
演示
let data = [
{
'key_1': 'value1A',
'key_2': 'value2A',
'key_3': 'value3A'
},
{
'key_1': 'value1B',
'key_2': 'value2B',
'key_3': undefined,
}
],
arr = data.map((el) => {
return {'key_1': el['key_2'], 'key_2': 'key_3' in el ? el['key_3'] : ''};
});
console.log(arr);
关于javascript - 检查映射函数中的 JSON 响应中是否存在 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49696515/