在JavaScript中删除多个对象键值

塞特希:

我想知道如何删除的对象的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"
}
CertainPerformance:

你需要周围走另一条路-在对象上的所有按键迭代,如果不在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);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

TOP 榜单

热门标签

归档