gpt4 book ai didi

Javascript/Typescript - 从对象中删除

转载 作者:行者123 更新时间:2023-11-28 13:07:54 24 4
gpt4 key购买 nike

如何删除包含 filter1 的所有对象?

const obj = {
0: {
'filter1': {
'key1': {
'email1': 'email1'
}
}
},
1: {
'filter1': {
'key12': {
'email12': 'email12'
}
}
},
2: {
'filter2': {
'key2': {
'email2': 'email2'
}
}
}
}

最佳答案

您可以使用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);

或者如 @zerkms说,使用 entries :

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);

关于Javascript/Typescript - 从对象中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45204810/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com