Select or Omit Properties From an Object in JavaScript

Select or Omit Properties From an Object in JavaScript:

 

https://ift.tt/2UgvLrq


Selecting Properties From An Object

If we want to select any number of properties from a JavaScript object, we can implement the following pick function:

function pick(obj, ...props) {
  return props.reduce(function(result, prop) {
    result[prop] = obj[prop];
    return result;
  }, {});
}
Enter fullscreen mode Exit fullscreen mode

Let’s see this in action! Our first argument to the pick function will be the object we want to pick from and the subsequent arguments will the the names of the keys we want to keep.

const person = {
  name: 'Pete',
  dog: 'Daffodil',
  cat: 'Omar',
};

const dogPerson = pick(person, 'name', 'dog');

console.log(dogPerson);
// { name: "Pete", dog: "Daffodil" }
Enter fullscreen mode Exit fullscreen mode

We see that by providing the person object as the first argument and then the strings "name" and "dog" as the subsequent arguments, we’re able to retain the "name" and "dog" props from our object while disregarding the "cat" prop.

Omitting Properties From An Object

If we want to omit any number of properties from a JavaScript object, we can implement the following omit function:

function omit(obj, ...props) {
  const result = { ...obj };
  props.forEach(function(prop) {
    delete result[prop];
  });
  return result;
}
Enter fullscreen mode Exit fullscreen mode

Again, let’s use the same person object to see this in action.

const person = {
  name: 'Pete',
  dog: 'Daffodil',
  cat: 'Omar',
};

const catPerson = omit(person, 'dog');

console.log(catPerson);
// { name: "Pete", cat: "Omar" }
Enter fullscreen mode Exit fullscreen mode

We can see that, by providing our person object as the first argument and the string "dog" as the second argument, we’re able to get a new object with the "dog"property omitted!

https://ift.tt/2UgvLrq

from Tumblr https://generouspiratequeen.tumblr.com/post/632504998038831104

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s