[英]how to filter object in javascript using filter function?
I am trying to filter javascript object using filter function .But I am getting error key is not defined .here is my code https://jsfiddle.net/13n8n3om/ 我正在尝试使用过滤器功能过滤javascript对象。但是我没有定义错误键。这是我的代码https://jsfiddle.net/13n8n3om/
var arr=[
{
"EX": {
"division": "abc",
"is_active": true,
}
},
{
"PY": {
"division": "pqwww",
"is_active": false,
}
}
];
arr = arr.filter(function(obj) {
return obj[key] !== 'EX';
});
console.log(arr)
Expected output 预期产量
[
{
"PY": {
"division": "pqwww",
"is_active": false,
}
}
]
replace 更换
return obj[key] !== 'EX';
with 与
return Object.keys(obj)[0] !== 'EX';
basically you need to access the first property of obj
and key is undefined. 基本上,您需要访问
obj
的第一个属性,并且键是未定义的。
Just check the key of the object if it is unequal with the given string. 只需检查对象的键是否与给定的字符串不相等。
var arr = [{ "EX": { "division": "abc", "is_active": true, } }, { "PY": { "division": "pqwww", "is_active": false, } }]; arr = arr.filter(function (obj) { return Object.keys(obj)[0] !== 'EX'; }); document.write('<pre>' + JSON.stringify(arr, 0, 4) + '</pre>');
You need to check that the obj
isn't EX
like so : 您需要检查
obj
是否不是EX
例如:
arr = arr.filter(function(obj, key) {
if (! obj.EX) {
return obj;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.