0

This should be simple, but I'm hitting a wall:

I need to take this object:

{
  'a': 'foo', 
  'b': 'bar', 
  'c': 'baz',
  'd': 'moo'
  // etc...
  'z': 'farfegnugen'
}

And REMOVE the items with keys matching an unknown list: {'a', 'c', 'f'} or just {'a'}...

Trees4theForest
  • 1,267
  • 2
  • 18
  • 48

3 Answers3

1

You are probably looking for the JS delete operator and iterate over the list as follows and iterate trough the array with the foreach function:

toDelete.forEach(function (key){
    delete object[key];
});
Elias Schablowski
  • 2,619
  • 9
  • 19
  • Ha! I'm thinking about looping through the inital object, but you rocked my world with "why not loop through the target keys". Must be getting late :P – Trees4theForest Jun 04 '20 at 04:14
  • If you want to loop through an object you can either use [Object.keys](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) or `for(let key in object){...}` (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) – Elias Schablowski Jun 04 '20 at 04:20
1

This will work:

var removeList = ['a', 'c', 'f'];
var object = {
  'a': 'foo', 
  'b': 'bar', 
  'c': 'baz',
  'd': 'moo',
  'z': 'farfegnugen'
};

removeList.forEach((key) => {
    delete object[key];
});
Udbhav
  • 212
  • 1
  • 6
0

Use filter on Object.entries instead of mutating the object.

const filterRemove = (obj, list) =>
  Object.fromEntries(
    Object.entries(obj).filter(([key]) => !list.includes(key))
  );

const obj = {
  a: "foo",
  b: "bar",
  c: "baz",
  d: "moo",
  z: "farfegnugen",
};

console.log(filterRemove(obj, ["a", "c"]));
Siva K V
  • 10,561
  • 2
  • 16
  • 29