How to filter JS Object properties

I was working in a React JS project and going to develop a higher order component to extend some feature of another component which is provided by a UI library. There is a Filter method in JS which works only with Array. First thing came into my mind is the old school approach like below.

const profile = {
  name: "Daniel Dör",
  age: 34,
  eyeColor: "brown",
  height: "172cm",
  address: "49.872660, 8.654226",
  hairColor: "brown",
  carBrand: "BMW"
};

let filtered = {};

Object.keys(profile).map(item => {
  if (item !== "carBrand" && item !== "hairColor") {
    return (filtered[item] = profile[item]);
  }
});

console.log(filtered);

/*
[object Object] {
  address: "49.872660, 8.654226",
  age: 34,
  eyeColor: "brown",
  height: "172cm",
  name: "Daniel Dör"
}
*/

This is fine but now we have a really nicer way to achieve the same thing. It is the Object destructuring. With this new ES6 syntax we can do this like below.

const profile = {
  name: "Daniel Dör",
  age: 34,
  eyeColor: "brown",
  height: "172cm",
  address: "49.872660, 8.654226",
  hairColor: "brown",
  carBrand: "BMW"
};

const {carBrand, hairColor, ...others} = profile;

console.log(others);

/*
[object Object] {
  address: "49.872660, 8.654226",
  age: 34,
  eyeColor: "brown",
  height: "172cm",
  name: "Daniel Dör"
}
*/

How is it happening?

After the const keyword in curly braces, I mentioned the properties names which can be used later. This is how we define a lot of variables fast to use them easily without chaining an Object so often. In this way, you are pulling some specific item from that Object. If you add a property at the end of the curly braces with spread operator (…) it will contain all the properties of the targeted Object except the ones mentioned just before it.

I am saying curly braces just avoid misunderstanding with two Object here. I hope it is clear enough.

Using underscore

If you are using ES5 and don’t have the possibility to use ES6 but still looking for a nicer solution then I would suggest using Lodash.

Using Pick

var profile = {name: 'moe', age: 50, userid: 'moe1'};
_.pick(profile, 'name', 'age');

// Output: {name: 'moe', age: 50}

Using Omit

var profile = {name: 'moe', age: 50, userid: 'moe1'};
_.omit(profile, 'userid');

// Output: {name: 'moe', age: 50}