gpt4 book ai didi

javascript - 在javascript中删除多个对象键值

转载 作者:行者123 更新时间:2023-12-04 10:29:17 25 4
gpt4 key购买 nike

我想知道如何删除对象 javascript 中的多个键。
如何删除obj中的日期键。

var obj ={
"id": "1",
"cn": "TH",
"curr": "THB",
"10-02-2020": "10,11",
"12-01-2019": "2,5"
}

var result = filterkeys(obj,["id","cn","curr"]);

function filterkeys(obj,arr){
arr.forEach(function(key) {
delete !obj[key];
});
return obj;
}


预期输出:
{
"id": "1",
"cn": "TH",
"curr": "THB"
}

最佳答案

你需要反过来——遍历对象的所有键,如果它不在 arr 中, 删除它:

var obj ={
"id": "1",
"cn": "TH",
"curr": "THB",
"10-02-2020": "10,11",
"12-01-2019": "2,5"
}

var result = filterkeys(obj,["id","cn","curr"]);

function filterkeys(obj,arr){
for (const key of Object.keys(obj)) {
if (!arr.includes(key)) {
delete obj[key];
}
}
return obj;
}

console.log(result);


或者,没有 delete (可能更好地避免 delete 可能的话 - 最好避免突变) - 映射键数组以使用 Object.fromEntries 构造一个新对象:

var obj ={
"id": "1",
"cn": "TH",
"curr": "THB",
"10-02-2020": "10,11",
"12-01-2019": "2,5"
};
const filterkeys = (obj,arr) => Object.fromEntries(
arr.map(key => [key, obj[key]])
);

var result = filterkeys(obj,["id","cn","curr"]);

console.log(result);

关于javascript - 在javascript中删除多个对象键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60482408/

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