我有以下代码:
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (obj[key].id === foo.id) {
// do something
}
}
}
在执行任何功能之前,我会检查对象是否不为空,因为该数组稍后会在用户交互时填充。
为了更好的可读性,我想做这样的事情:
const result = obj.filter((item) => item.id === foo.id)
return result[0]
但是,这会产生错误:obj.filter 不是函数
,因为该对象在页面呈现时为空,稍后会填充。
问题是 - 如何简化这个过程,同时防止以最简单的方式过滤空对象?
编辑:添加 obj
的示例数据结构
{
0: { id: 2, name: 'John', category: 'Repair' },
1: { id: 3, name: 'William', category: 'Maintenance' }
}
最佳答案
您可以使用空数组作为默认值。
const result = (obj || []).filter(item => item.id === foo.id);
或使用 Array.isArray
进行显式检查.
const result = Array.isArray(obj) && obj.filter(item => item.id === foo.id);
结果是一个数组或false
。
如果您想获取空数组,也可以使用数组作为默认值,例如
const result = Array.isArray(obj) && obj.filter(item => item.id === foo.id) || [];
现在,在给出对象的结构后,您可以使用
var getItem = (obj, id) => obj && typeof obj === 'object' && Object
.keys(obj)
.filter(key => obj[key].id === id)
.map(key => obj[key]),
obj = {
0: { id: 2, name: 'John', category: 'Repair' },
1: { id: 3, name: 'William', category: 'Maintenance' }
},
result1 = getItem(obj, 3),
result2 = getItem(null, 3);
console.log(result1);
console.log(result2);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 防止过滤空 JS 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44428730/