1

I have an object with some properties. I would like to extract a few well-know properties, skipping over any that are not present.

Something like this:

let x = {a: 1, b: 2, c: 3};
let y = take a, b, d from x; // Not real JS!

With y now looking like this:

{a: 1, b: 2} // Note that d is missing!

Is there an operator or method that does this?

Luka Jacobowitz
  • 19,651
  • 5
  • 34
  • 54
sdgfsdh
  • 24,047
  • 15
  • 89
  • 182

3 Answers3

4

Another way to do it is by destructuring:

let {a, b, d} = x;
let y = {a, b, d};

This automatically takes out the properties you want to use. Then you can put them back together with an object literal, which in ES6 doesn't require you to do { a: a, b : b }. You can just write { a, b } instead, if the names are the same.

In this case, a, b and d are also copied.

Luka Jacobowitz
  • 19,651
  • 5
  • 34
  • 54
0

Try the following -

out = {a: in.a, b:in.b, d:in.d};
out = JSON.parse(JSON.stringify(out));
jaibatrik
  • 5,072
  • 6
  • 28
  • 60
0
var copied = {};
var propertiesToCopy = ['a', 'b'];
for (var key in originalObject) {
  if (originalObject.hasOwnProperty(key) && propertiesToCopy.indexOf(key) != -1) {
    copied[key] = originalObject[key];
  }
}
Bruno
  • 232
  • 1
  • 8