1

So in es6, I can pass values of properties to a variable with same name like this:

let luke = { occupation: 'jedi', father: 'anakin' }
let {occupation} = luke

console.log(occupation); // 'jedi'

but what if, I want to set a value of a property inside an object too? Like this...

let luke = { occupation: 'jedi', father: 'anakin' }
let someObject = { occupation: null }

I can simply do it with someObject.occupation = luke.occupation, but is it possible to do it with object destructing in es6?

wobsoriano
  • 8,501
  • 19
  • 63
  • 125
  • 1
    If you end goal is to just have an object with your desired properties, you can always just spread the two objects together. But this creates a new object, as opposed to mutating the existing one. – Andrew Nov 17 '17 at 04:41
  • This may be what @Andrew was suggesting. `let { occupation } = luke; let obi = { occupation };` – fubar Nov 17 '17 at 05:07
  • @fubar I mean this: `{...luke, ...someObject}`. But what I don't like about this approach is that order matters. If `someObject` is not the second object in your spread, it won't overwrite the key that's in `luke`. – Andrew Nov 17 '17 at 05:10
  • 1
    @Andrew - yep, sure. And so if `occupation` is initialized to `null`, spreading won't work. You could do `let { occupation } = luke; let o = { ...o, occupation }; – fubar Nov 17 '17 at 05:14
  • @fubar Totally overlooked that. I even use that all the time. Good catch. FewFlyBy, do you need a formal answer still? – Andrew Nov 17 '17 at 05:20
  • @Andrew: Object rest/spread is not part of ES6 anyway. – Felix Kling Nov 17 '17 at 05:46
  • Possible duplicate of [One-liner to take some properties from object in ES 6](https://stackoverflow.com/q/25553910/218196) – Felix Kling Nov 17 '17 at 05:46
  • Every couple of days a similar question like this one is asked. The general answer is: Destructuring is for creating local variables from object properties / array elements. It's not meant for generating a subset of properties / elements. – Felix Kling Nov 17 '17 at 05:48
  • @FelixKling Are you sure? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator. What does the specifications table mean then? – Andrew Nov 17 '17 at 05:52
  • 1
    @Andrew: 100% sure. [You can look at the ES6 spec](https://www.ecma-international.org/ecma-262/6.0/) and see that it doesn't mentioned anything about object rest/spread. The table says *"Rest/Spread Properties for ECMAScript Draft Stage 3 draft."* It means that the proposal is in stage 3. Every proposal [goes through multiple stages](https://tc39.github.io/process-document/). It's finished (and will be included in the one of the next releases) if it reaches stage 4. – Felix Kling Nov 17 '17 at 05:58
  • @FelixKling Noted, much thanks – Andrew Nov 17 '17 at 06:00

0 Answers0