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?
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With