0

How can I do the following scenario in ES6

const x = {a: 10, aa: 100, b: 20, bb: 200}
const AA = {
  a: x.a,
  aa: x.aa
}
const BB = {
  b: x.b,
  bb: x.bb
}

I am expecting something like

const x = {a: 10, aa: 100, b: 20, bb: 200}
const AA = ({ a, aa } from x)
const BB = ({ b, bb } from x)
SRAVAN
  • 379
  • 3
  • 11

2 Answers2

0

You could either define the const AA and BB first...

const AA = {}, BB = {};
const x = {a: 10, aa: 100, b: 20, bb: 200};
({a: AA.a, aa: AA.aa, b: BB.b, bb: BB.bb} = x);

...or you could destructure object first and then define AA and BB with the destructured variables:

const x = {a: 10, aa: 100, b: 20, bb: 200}
const {a, aa, b, bb} = x;
const AA = {a, aa};
const BB = {b, bb};
nils
  • 20,884
  • 5
  • 60
  • 75
  • Thanks for the response nils. I was looking for some easy ways. Seems http://underscorejs.org/#pick or some similar function can help me as there is no inbuilt way in ES6 – SRAVAN Apr 28 '16 at 11:44
0

Object destructuring is the wrong tool for this job. What you want is sometimes called "pluck" and can be easily implemented as:

function pluck(obj, ...props) {
  const result = {};
  for (let prop of props) {
    result[prop] = obj[prop];
  }
  return result;
}

const AA = pluck(x, 'a', 'aa');
const BB = pluck(x, 'b', 'bb');
Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072
  • I knew underscore's pick could do the trick. I was wondering ES6 has some syntax for this. Now Its clear to me that there is no such in built thing!. Thanks for the response! Ref: http://underscorejs.org/#pick – SRAVAN Apr 28 '16 at 11:41