4

Say I have an object foo with properties a and b but I want to transfer the values of these properties to another object bar with properties x and y where bar.x gets the value of foo.a and bar.y gets the value of foo.b.

The first way that comes to mind to accomplish this with ES5 would be like the following.

var foo = { a: 5, b: 17 };
var bar = { x: foo.a, y: foo.b };

This is already pretty terse but having to reference foo in each case to access it's properties gets noisy for a larger property mapping. Looking in to the new destructuring features in ES6 it seems that it is possible to destructure nested objects into a flattened set of variables but I haven't found any examples which point out the ability to specify an object in which to destructure property values instead. Does this feature not exist or have I just not found the example that shows how this is done? If it is not possible are there any other clever tricks that can be done to achieve a similar result?

To be clear I was hoping to be able to do something along the lines of the example below.

var foo = { a: 5, b: 17 };
var bar = { a: x, b: y } = foo;

This question is different from (One-liner to take some properties from object in ES 6) because I'm looking for a way to avoid writing foo and not the property list. In fact keeping the property list for explicit mapping is my goal.

Community
  • 1
  • 1
jpierson
  • 13,736
  • 10
  • 94
  • 137
  • 1
    You can use *with*: `with (foo) var bar = { x: a, y: b };` but be careful of zealots… – RobG Feb 18 '16 at 02:19
  • 3
    Be wary of those "zealous" red disclaimers in the [docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with) ... "Use of the with statement is not recommended, as it may be the source of confusing bugs and compatibility issues. See the "Ambiguity Contra" paragraph in the "Description" section below for details." – Thank you Feb 18 '16 at 07:52
  • 1
    @naomik—"the docs" you reference is a public wiki maintained by anyone who cares to contribute. The only authority is the specification, ECMA-262, which has no similar statements (though I agree that in general, *with* should be avoided). – RobG Feb 18 '16 at 09:23
  • 4
    @RobG: note that `with` is disallowed in strict mode. And ES6 modules are always strict. – Felix Kling Feb 18 '16 at 14:31

1 Answers1

2

Destructuring assignment allows you to do this pretty easily

let foo = {a: 5, b: 17, c: 10};
let {a,b,c} = foo;
let bar = {x: a, y: b, c};
console.log(bar);
// => {x:5, y:17, c:10}
Thank you
  • 107,507
  • 28
  • 191
  • 224
  • So the idea is to pull things you want into local scope as variables and then structure those variables into a new object? This seems reasonable but I would be interested in the performance impact of shuffling the values around compared to working original not so terse example in my original post. – jpierson Feb 18 '16 at 09:02