Reputation:
It's convenient to extract properties from Object
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 Object
s with computed patterns?
Upvotes: 5
Views: 1510
Reputation: 26161
I had written a standard reusable Object method to access nested properties dynamically. You can use this on any object to access your nested value. It's called Object.prototype.getNestedValue()
Object.prototype.getNestedValue = function(...a) {
return a.length > 1 ? (this[a[0]] !== void 0 && this[a[0]].getNestedValue(...a.slice(1))) : this[a[0]];
};
So once you have this it's very easy. It will take dynamic arguments for the nested properties. If they are string type they are object properties if number type then they are array indices. Once you have this, your job becomes very easy. Let's see..
Object.prototype.getNestedValue = function(...a) {
return a.length > 1 ? (this[a[0]] !== void 0 && this[a[0]].getNestedValue(...a.slice(1))) : this[a[0]];
};
let o = {id: "100", name: "Jane Doe", address: {id:1, city:"Fargo"}},
props = ["address","city"],
v = o.getNestedValue(...props);
console.log(v);
// you can also pass static parameters of course...
v = o.getNestedValue("address","city");
console.log(v);
You can see getNestedValue() and it's twin setNestedValue() working at https://stackoverflow.com/a/37331868/4543207
Upvotes: -1
Reputation:
No, it's not possible. JavaScript has no concept of these "object paths" like "p1.p2"
that people seem to be so enamored of, whether it be in the context of destructuring or anywhere else.
Upvotes: 2
Reputation: 664297
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.
Upvotes: 4