5 ways to get a subset of object properties in javascript

Learn How to create a subset of a javascript object with examples.

Let’s have a javascript object

let user = {
  id: 11,
  name: "frank",
  salary: 5000,
  active: true,
  roles: ["admin", "hr"],
};

Simple to create a partial set of attributes

Let’s create a new object initializing existing partial properties as seen below.

var userinfo = { id: user.id, name: user.name };
console.log(userinfo);

output

{ id: 11, name: 'frank' }

This needs a lot of code lines if the object has many properties

get some properties using reduce method

With an empty object, using an array.reduce method iterate the subset of keys and values and store it in a new array with required properties.

const subset = ["id", "name"].reduce((result, key) => {
  result[key] = user[key];
  return result;
}, {});

using es6 destructuring assignment

ES6 has a new syntax destructuring assignment operator.

It returns the result of a subset of an object.

let [id, name] = user;
const userinfo = { id, name };
console.log(userinfo);

Underscore pick method

pick() method in the underscore library is used to return the subset of a user object with given keys.

Here is a syntax

_.pick(javascriptobject, multiplekeys);
  • javascriptobject - javascript object
  • multiplekeys - an array of keys

here is an example

var userinfo = _.pick(user, "name", "salary");

Output:

{ name: 'frank', salary:5000 }

Lodash has also the same pick() function which also works the same way.