从对象中删除特定键 [英] Removing specific keys from an object

查看:65
本文介绍了从对象中删除特定键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定像["a","r","g"]之类的元素数组和一个对象,我试图删除其中键是数组元素的键/值对.

Given an array of elements like ["a","r","g"] and an object, I am trying to remove the key/value pairs where the keys are elements of the array.

function shorten(arr, obj) {
  
  var keys = Object.keys(obj);          //make an array of the object's keys
  for(var i = 0; i < arr.length; i++)   //loop for original array (arr) 
      for(var j = 0; j < keys.length; j++)  //loop for "keys" array
          if(arr[i] === obj[keys[j]])           //check for array element matches
              delete obj[keys[j]];                  //delete the matches from object
  return obj;                           //return the new object
    
}

 var arrA = ['a','r', 'g'];
 var oB = {a: 4, u: 1, r: 2, h: 87, g: 4};
 console.log(shorten(arrA,oB))         //I keep getting the original object
                                       //The function isn't shortening things

//desired output is:

{u: 1, h: 87}

对于任何阅读并可以帮助我的人,请先谢谢您.

To anyone that reads this and can help me out, thank you in advance.

推荐答案

您的代码无法正常工作的原因是,它会将属性的与属性名称( a 4 等)

The reason your code isn't working is it's comparing the value of the property with the property's name (a with 4, etc.)

假设您确实要删除数组中列出的属性(即您所说的,而不是您希望的输出所显示的内容),则该代码可以更简单地很多,因为 delete 如果对象不具有以下属性,则为空操作

Assuming you really want to delete the properties listed in the array, which is what you said but not what your desired output suggests, the code can be a lot simpler, since delete is a no-op if the object doesn't have the property:

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

var arrA = ['a','r', 'g'];
var oB = {a: 4, u: 1, r: 2, h: 87, g: 4};
console.log(shorten(arrA, oB));

旁注:通常并不重要,但是值得注意的是,在某些JavaScript引擎的对象上使用 delete 会使该对象上的后续属性查找操作变慢.引擎已经过优化,可以处理正在被添加,更新但未被删除的属性.删除属性后,它会禁用某些JavaScript引擎对属性查找所做的优化.当然,通常这没关系...

Side note: It usually doesn't matter, but it's worth noting that using delete on an object on some JavaScript engines makes subsequent property lookup operations on that object much slower. Engines are optimized to handle properties being added and updated, but not removed. When a property is removed, it disables the optimizations some JavaScript engines do on property lookup. Of course, again, it usually doesn't matter...

这篇关于从对象中删除特定键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆