简体   繁体   English

嵌套对象的计算解构

[英]Computed destructuring of nested Objects

It's convenient to extract properties from Object s by destructuring: 通过解构从Object s中提取属性很方便:

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? 是否可以用计算模式来构造嵌套的Object

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. 请参阅问题将点符号中的JavaScript字符串转换为对象引用以及其他许多内容。

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. JavaScript没有像"p1.p2"这样的“对象路径”的概念,人们似乎非常迷恋它,无论是在解构还是其他任何地方。

I had written a standard reusable Object method to access nested properties dynamically. 我编写了一个标准的可重用Object方法来动态访问嵌套属性。 You can use this on any object to access your nested value. 您可以在任何对象上使用它来访问嵌套值。 It's called Object.prototype.getNestedValue() 它叫做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 您可以在https://stackoverflow.com/a/37331868/4543207上看到getNestedValue()和它的双setNestedValue()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM