Thimma
Thimma

Reputation: 1492

How would one remove all keys on an object which are not present in an Array in JavaScript?

Let's say I got this array

const items = ["foo", "bar", "baz"];

and I got this object

const _obj = {
  foo: [1, 2, 3],
  bar: [1, 2, 3],
  baz: [1, 2, 3],
  moo: [1, 2, 3],
  tee: [1, 2, 3]
};

I would like to have all the object keys removed which are not present in the items array.

So the result should be:

const _newObj = {
  foo: [1, 2, 3],
  bar: [1, 2, 3],
  baz: [1, 2, 3]
}

As you can see, the properties moo and tee are not present in the object anymore, since they are not items of the array.

I will use it like this:

const [obj, setObj] = useState({
  foo: [1, 2, 3],
  bar: [1, 2, 3],
  baz: [1, 2, 3],
  moo: [1, 2, 3],
  tee: [1, 2, 3]
});

const update = () => {
  setObj(prevObj => {
    // the magic should happen here
    return { ...prevObj };
  });
}

How would I accomplish this..?

Upvotes: 3

Views: 532

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386560

You could map new entries and get a new object from it.

const
    items = ["foo", "bar", "baz"],
    object = { foo: [1, 2, 3], bar: [1, 2, 3], baz: [1, 2, 3], moo: [1, 2, 3], tee: [1, 2, 3] },
    result = Object.fromEntries(items.map(key => [key, object[key]]));

console.log(result);

A version which keeps the same object reference.

const
    items = ["foo", "bar", "baz"],
    object = { foo: [1, 2, 3], bar: [1, 2, 3], baz: [1, 2, 3], moo: [1, 2, 3], tee: [1, 2, 3] };

Object
   .keys(object)
   .filter(key => !items.includes(key))
   .forEach(Reflect.deleteProperty.bind(null, object));

console.log(object);

Upvotes: 1

Jens Stragier
Jens Stragier

Reputation: 223

You can use the "hasOwnProperty" function to detect if that object has a property by a certain name. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

Dummy code:

for (int i = 0; items.length; i++) {
    if (_obj.hasOwnProperty(items[i]) {
            delete _obj[items[i]];
        }
    }
}

If you want it to be a new object, you could build the object instead of doing a delete on the existing one. hasOwnProperty is supported in all browsers, where the other answer (fromEntries) will require a polyfill for Internet Explorer.

Upvotes: 0

mgm793
mgm793

Reputation: 2066

Maybe using reduce:

const _newObj = Object.entries(_obj).reduce((acc, el) => {
  const [key, value] = el;
  if(items.includes(key)){
    acc[key] = value;
  }
  return acc;
},{});

Upvotes: 0

Related Questions