1

Is it somehow possible to destructure an object, set a default value, and assign this default value directly to the object's property?

Consider this code

let foo = {};
let {bar = 1} = foo;
console.log(foo); // {}
console.log(bar); // 1

As you can see, foo still doesn't have a bar property. Is there something like below possible, to assign the prop and default value directly to the object:

let {bar = 1: foo.bar}

This is obvious illegal syntax.

Is there any one liner I can use to get foo to be

{bar: 1}

after the destructuring is done?

4
  • what do you mean by destructuring? Are you talking about inheritance here in some way? Commented Jun 7, 2018 at 9:58
  • 1
    @RehanUmar I mean developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jun 7, 2018 at 9:58
  • You can use spread syntax to add new object props to existing one , or you want to use destructuring in this case ? Commented Jun 7, 2018 at 10:01
  • Maybe inline if bar ? bar : 1 Commented Jun 7, 2018 at 10:18

1 Answer 1

2

You could take the object with property as target by using the object property assignment pattern [YDKJS: ES6 & Beyond].

var foo = {};

({ bar: foo.bar = 1 } = foo);
console.log(foo);

foo.bar = 42;
({ bar: foo.bar = 1 } = foo);
console.log(foo);

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. From what I've read this is the closest it will get. Do you see any chance to also define bar like it would have been in the question?
do you mean to get a variable bar and an assignment to the property at the same time? if so, i see no choice, because with only bar, you get a new variable, and with bar: foo.bar, it's part of the destructuring chain.
Yes exactly. I don't think it's possible either atm.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.