以下是一个数组:
var array = [ {"a":1, "b":2}, {"a":3, "b":3, "c":1}, {"a":9, "b":2}, {"a":7, "b":2}, {"a":1, "b":2, "c":6}];
我需要从数组中删除所有不包含"c"
键的对象。例如:
{"a":1, "b":2}, {"a":9, "b":2}, {"a":7, "b":2}
是来自数组的那些不包含"c"
键的对象。
请不要使用javascript的"delete"
运算符,因为它与我的项目中的要求不同。
预期输出:var array = [{"a":3, "b":3, "c":1}, {"a":1, "b":2, "c":6}];
答案 0 :(得分:0)
您可以使用过滤器执行此操作:
x = x.filter(o => 'c' in o);
var x = [ {"a":1, "b":2}, {"a":3, "b":3, "c":1}, {"a":9, "b":2}, {"a":7, "b":2}, {"a":1, "b":2, "c":6} ];
x = x.filter(o => 'c' in o);
console.log(x);
.as-console-wrapper { max-height: 100% !important; top: 0; }
如果您没有ES6支持:
x = x.filter(function(o) {
return 'c' in o;
});
答案 1 :(得分:0)
您只需使用内置过滤功能。
使用Lambda:
var x = [ {"a":1, "b":2}, {"a":3, "b":3, "c":1}, {"a":9, "b":2}, {"a":7, "b":2}, {"a":1, "b":2, "c":6}];
var filteredX = x.filter(obj => obj.c !== void 0);
console.log(filteredX);
正常函数语法:
var x = [ {"a":1, "b":2}, {"a":3, "b":3, "c":1}, {"a":9, "b":2}, {"a":7, "b":2}, {"a":1, "b":2, "c":6}];
var filteredX = x.filter(function(obj){
return obj.c !== void 0;
});
console.log(filteredX);
答案 2 :(得分:0)
您可以先获得公共密钥,然后根据密钥创建新的对象。
var array = [{ a: 1, b: 2 }, { a: 3, b: 3, c: 1 }, { a: 9, b: 2 }, { a: 7, b: 2 }, { a: 1, b: 2, c: 6 }],
common = array.reduce(function (r, o, i) {
var keys = Object.keys(o);
return i ? r.filter(function (k) { return keys.indexOf(k) + 1; }) : keys;
}, []),
result = array.map(function (a) {
var o = {};
common.forEach(function (k) {
o[k] = a[k];
});
return o;
});
console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 3 :(得分:0)
使用javascript的过滤方法:
Var newArray= array.filter(function(elem, i, array). {
return element.hasOwnProperty("c");
}
);