Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a subset of a javascript object's properties

Say I have an object:

elmo = {    color: 'red',   annoying: true,   height: 'unknown',   meta: { one: '1', two: '2'} }; 

I want to make a new object with a subset of its properties.

 // pseudo code  subset = elmo.slice('color', 'height')   //=> { color: 'red', height: 'unknown' } 

How may I achieve this?

like image 904
Christian Schlensker Avatar asked Jul 22 '13 06:07

Christian Schlensker


People also ask

How do I extract properties from an object?

We have to write a JavaScript function, say extract() that extracts properties from an object to another object and then deletes them from the original object.

Which syntax is a subset of JavaScript object?

To get the subset of properties of a JavaScript Object, we make use of destructuring and Property Shorthand. The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Can you filter an object JavaScript?

JavaScript's Objects are not iterable like arrays or strings, so we can't make use of the filter() method directly on an Object . filter() allows us to iterate through an array and returns only the items of that array that fit certain criteria, into a new array.


1 Answers

Using Object Destructuring and Property Shorthand

const object = { a: 5, b: 6, c: 7  };  const picked = (({ a, c }) => ({ a, c }))(object);    console.log(picked); // { a: 5, c: 7 }

From Philipp Kewisch:

This is really just an anonymous function being called instantly. All of this can be found on the Destructuring Assignment page on MDN. Here is an expanded form

let unwrap = ({a, c}) => ({a, c});    let unwrap2 = function({a, c}) { return { a, c }; };    let picked = unwrap({ a: 5, b: 6, c: 7 });    let picked2 = unwrap2({a: 5, b: 6, c: 7})    console.log(picked)  console.log(picked2)
like image 54
Ivan Nosov Avatar answered Sep 30 '22 10:09

Ivan Nosov