Iven Iven - 2 years ago 81
Javascript Question

Computed destructuring of nested Objects

It's convenient to extract properties from

s by destructuring:

let o = {id: "100", name: "Jane Doe", address: {id:1, city:"Fargo"}},
key = "address";

let {address: {id: id}} = o; // 1

Destructuring patterns can be computed as well:

let {[key]: {city: city}} = o; // Fargo

But it seems apparently not possible to extract properties of nested objects dynamically:

key = "address.city";
({[key]: city} = o); // undefined

Is it possible to destructure nested
s with computed patterns?

Answer Source

No, this is not possible. Destructuring is only for objects whose structure you know about. You could of course do

var keys = ["address", "city"];
var {[keys[0]]: {[keys[1]]: city}} = o;

but not for arbitrarily nested objects. You'll have to use a recursive function for that which walks the property path. See the question Convert JavaScript string in dot notation into an object reference and many others for that.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download