如何删除包含filter1
的所有对象?
const obj = {
0: {
'filter1': {
'key1': {
'email1': 'email1'
}
}
},
1: {
'filter1': {
'key12': {
'email12': 'email12'
}
}
},
2: {
'filter2': {
'key2': {
'email2': 'email2'
}
}
}
}
答案 0 :(得分:3)
易。
delete
API。hasOwnProperty
API。你在这里可以做的是。首先循环obj
中的所有键,然后检查其value
(一个对象)是否具有filter1
属性。如果他们那么delete
它就离开了。
示例:强>
const obj = {
0: {
'filter1': {
'key1': {
'email1': 'email1'
}
}
},
1: {
'filter1': {
'key12': {
'email12': 'email12'
}
}
},
2: {
'filter2': {
'key2': {
'email2': 'email2'
}
}
}
};
for (var key in obj) {
var objectInKey = obj[key];
if (objectInKey.hasOwnProperty("filter1")) {
delete obj[key]
}
}
console.log(JSON.stringify(obj, null, 4));
console.log(obj[0]); // <-- Should be undefined.
console.log(obj[2]); // <-- Should not be undefined as obj wasn't deleted.
答案 1 :(得分:2)
您可以使用reduce
获取新对象:
const newObject = Object.keys(obj).reduce((newObj, key) => {
if (!obj[key].filter1) {
newObj[key] = obj[key];
}
return newObj;
}, {});
const obj = {
0: {
'filter1': {
'key1': {
'email1': 'email1'
}
}
},
1: {
'filter1': {
'key12': {
'email12': 'email12'
}
}
},
2: {
'filter2': {
'key2': {
'email2': 'email2'
}
}
}
};
const newObject = Object.keys(obj).reduce((newObj, key) => {
if (!obj[key].filter1) {
newObj[key] = obj[key];
}
return newObj;
}, {});
console.log(newObject);
&#13;
const entries = Object.entries(obj).reduce((newObj, [key, val]) => {
if (val.filter1) {
return newObj;
}
return {
...newObj,
[key]: val,
}
}, {});
const obj = {
0: {
'filter1': {
'key1': {
'email1': 'email1'
}
}
},
1: {
'filter1': {
'key12': {
'email12': 'email12'
}
}
},
2: {
'filter2': {
'key2': {
'email2': 'email2'
}
}
}
};
const newObject = Object.entries(obj).reduce((newObj, [key, val]) => {
if (val.filter1) {
return newObj;
}
return {
...newObj,
[key]: val,
}
}, {});
console.log(newObject);
&#13;
答案 2 :(得分:0)
您可以使用Object.entries
获取一组键值对,然后使用Array#reduce
过滤数据并将其转换回对象格式。
const obj = {
0: { 'filter1': { 'key1': { 'email1': 'email1' } } },
1: { 'filter1': { 'key12': { 'email12': 'email12' } } },
2: { 'filter2': { 'key2': { 'email2': 'email2' } } }
};
console.log(Object.entries(obj).reduce((m, [k, v]) => (v.filter1 || (m[k] = v), m), {}));
// { "2": { "filter2": { "key2": { "email2": "email2" } } } }
&#13;
进一步阅读:
答案 3 :(得分:0)
要修改对象到位(而不是复制它或创建数组),我只使用一个简单的循环和删除:
let k = Object.keys(obj);
for (let i = 0; i < k.length ; i++ ) {
if (obj[k[i]].hasOwnProperty('filter1')) delete obj[k[i]];
}
答案 4 :(得分:-1)
您可以使用filter
,
obj = obj.filter(o => o.filter1 == undefined);
请参阅filter
参考here。
<强> P.S。此示例中的obj
为var
而不是const
,请参阅下面的代码段
var obj = [
{
'filter1': {
'key1': {
'email1': 'email1'
}
}
},
{
'filter1': {
'key12': {
'email12': 'email12'
}
}
},
{
'filter2': {
'key2': {
'email2': 'email2'
}
}
}
];
console.log(obj); // initial obj
obj = obj.filter(o => o.filter1 == undefined);
console.log(obj); // element with `filter1` property is now deleted
&#13;