简体   繁体   中英

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.

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

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


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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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