3

Is there an elegant solution to destructure an object without specifying all the object's properties?

I wondered if it was possible to use the spread operator but it seems like that's not possible because objects are not arrays!

I guess it may be considered a bad idea to blindly declare variables but I think this would be useful for very large objects.

2
  • What is it that you are trying to do exactly? The with construct could do that, but I would really not recommend it for various reasons. Destructuring was partially implemented to solve the with problem. Otherwise, there is a Object spread/rest proposal in ES7: github.com/sebmarkbage/ecmascript-rest-spread But spreading is not destructuring. Commented Apr 22, 2016 at 15:18
  • 1
    Consider what you achieve with this, and what you think you "save". You get a lot of variables that you can use below, but you "save" the declaration. What purpose does that serve? Wouldn't it be better just to add the properties to the destructured assignment when you start using them? Your code will look cleaner, and you won't have useless variables declared. Also, it's a smell to me if you have very large objects of which you need to read/mutate many properties in your code. Commented Apr 25, 2016 at 15:43

1 Answer 1

7

This is what the with(){} construction allowed:

var obj = {a: 1};
with (obj) {
  console.log(a);
}

This construct is however severely discouraged and basically deprecated (it throws an error in strict mode), because it has some major drawbacks:

  • Your code is hard to read, because it's impossible to tell apart 1) Variables from outer scopes 2) Local variables 3) Properties coming from the object.

  • Your code can't be optimized, because the JavaScript engine can't tell where your variables are coming from.

  • Your code is much harder to refactor, because if you introduce a property to your obj, it might shadow some existing local variable, exemple:


var obj = {};
var a = 1;
addSomeProperties(obj);
with (obj) {
  console.log(a); // the result here depends on whether or not "addSomeProperties" puts a property named "a" on "obj"
}

TL;DR version: you really don't want this, it makes your code brittle, hard to read&refactor. Just pick the pieces you want apart using the "normal" destructuring syntax.

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

1 Comment

"This construct is however severely discouraged and basically deprecated" It will also throw an error in strict mode.

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.