Filter an object based on an array JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

Let’s say. we have an array and an object like this −

const arr = ['a', 'd', 'f'];
const obj = {
   "a": 5,
   "b": 8,
   "c": 4,
   "d": 1,
   "e": 9,
   "f": 2,
   "g": 7
};

We are required to write a function that takes in the object and the array and filter away all the object properties that are not an element of the array. So, the output should only contain 3 properties, namely: “a”, “d” and “e”.

Let’s write the code for this function −

Example

const arr = ['a', 'd', 'f'];
const obj = {
   "a": 5,
   "b": 8,
   "c": 4,
   "d": 1,
   "e": 9,
   "f": 2,
   "g": 7
};
const filterObject = (obj, arr) => {
   Object.keys(obj).forEach((key) => {
      if(!arr.includes(key)){
         delete obj[key];
      };
   });
};
filterObject(obj, arr);
console.log(obj);

Output

The output in the console will be −

{ a: 5, d: 1, f: 2 }
raja
Published on 26-Aug-2020 11:04:53
Advertisements