Categories
JavaScript Answers

How to Get a Subset of a JavaScript Object’s Properties?

Spread the love

Sometimes, we may want to get a subset of JavaScript properties from an object.

In this article, we’ll look at ways to get a subset of JavaScript object’s properties to a place where we can use them.

Object Destructuring

The shortest and easiest way to get a subset of a JavaScript object’s properties is to use the object destructuring syntax.

For instance, we can write:

const object = {
  a: 1,
  b: 2,
  c: 3
};
const {
  a,
  b
} = object
const picked = {
  a,
  b
}
console.log(picked)

We have an object with properties a , b , and c .

To get the properties, we can destructure them to assign them to their own variables.

We did that with:

const {
  a,
  b
} = object

Now a is assigned to object.a .

And b is assigned to object.b .

Then we can put them into another object with:

const picked = {
  a,
  b
}

And so picked is:

{a: 1, b: 2}

We can also do destructuring in function parameters.

For instance, we can write:

const object = {
  a: 1,
  b: 2,
  c: 3
};
const pick = ({
  a,
  b
}) => ({
  a,
  b
})
const picked = pick(object);
console.log(picked)

to create a pick function that returns an object with the a and b properties destructured from the object parameter.

So when we call pick with object , we get that picked is the same as before.

Lodash

We can also use Lodash’s pick method to return an object with the given properties.

For instance, we can write:

const object = {
  a: 1,
  b: 2,
  c: 3
};
const picked = _.pick(object, ['a', 'b']);
console.log(picked)

We call pick with the object to extract properties from.

And the array has the property name strings we want to get.

So picked is the same as the other examples.

Array.prototype.reduce

We can use the JavaScript array reduce method to get the properties from an object and put them into another object.

For instance, we can write:

const object = {
  a: 1,
  b: 2,
  c: 3
};
const picked = ['a', 'b'].reduce((resultObj, key) => ({
  ...resultObj,
  [key]: object[key]
}), {});
console.log(picked)

We call reduce on the [‘a’, ‘b’] array which are the property name strings for the properties we want to get from object .

resultObj has the object with the picked properties.

key has the key we want to get from the array.

We return an object with resultObj spread and the key with its corresponding value appended to the end of it.

The 2nd argument of reduce is an empty object so we can spread the properties into it.

And so picked has the same result as before.

Conclusion

We can get a subset of the properties of JavaScript wit destructuring assignment, array reduce , or the Lodash pick method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *