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.
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"]
};
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
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; }, {});
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)
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)
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.
🧮 Tags
Recent posts
Julia examples - Variable Type Nim example - Convert String to/from the Int How to get length of an array and sequence in Nim? Nim environment variables - read, set, delete, exists, and iterate examples? How to convert from single character to/from string in Nim?Related posts