5 ways to get a subset of a object properties in javascript


In this short tutorial, We are going to learn How to create a subset of javascript object with examples.

Let’s have an 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);
```markup
output
```markup
{ id: 11, name: 'frank' }

This needs lot of code lines if object has many properties

get some properties using reduce method

With empty object, using array.reduce method iterate the subset of keys and values store it 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 subset of an object.

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

Underscore pick method

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

Here is an syntax

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

here is an example

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

Output:

{ name: 'frank', salary:5000 }

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

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.