Iven Iven - 1 year ago 39
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?


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.