简体   繁体   English

从对象中删除特定键

[英]Removing specific keys from an object

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. 给定元素数组,例如[“ a”,“ r”,“ g”]和一个对象,我试图删除键/值对,其中键是数组的元素。

 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. 对于阅读此书并可以帮助我的任何人,在此先感谢您。

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.) 您的代码无法正常工作的原因是,它会将属性的与属性的名称(带有4 a等)进行比较。

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: 假设你真的要删除的磁盘阵列,这是你说的什么,但不是你所期望的输出有什么,该代码可以是简单了很多在列出的属性,因为delete是如果对象不具有财产无操作:

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


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. 旁注:通常这并不重要,但值得注意的是,在某些JavaScript引擎上的对象上使用delete会使该对象上的后续属性查找操作变慢。 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. 删除属性后,它将禁用某些JavaScript引擎对属性查找所做的优化。 Of course, again, it usually doesn't matter... 当然,通常,这并不重要...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM