本文介绍了如何解构对象的属性和属性的属性. ES6 Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象

const complicatedObject = {
  propertyA: {
    property1: 1,
    property2: 2
  },
  propertyB: {
    property1: 1,
    property2: 2
  }
}

如果我想抓住propertyA我愿意

const { propertyA } = complicatedObject

console.log(propertyA) // { property1: 1, property2: 2}

如果我想获取propertyA's property1值,我会

If I want to grab propertyA's property1 value I do

const { propertyA: { property1 } } = complicatedObject

console.log(property1) // 1

我可以这样抓住propertyApropertyA's property1.

const {
  propertyA,
  propertyA: {
    property1
  }
} = complicatedObject

console.log(propertyA) // { property1: 1, property2: 2}
console.log(property1) // 1

是否有更简单的方法同时获取propertyAproperty1?

Is there a simpler way to get both propertyA and property1?

我阅读了以下内容,但我觉得没有什么可以作为答案了.

I read the following but I felt like nothing jumped out to me as being the answer.

  • https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/
  • http://exploringjs.com/es6/ch_destructuring.html#sec_more-obj-destructuring

谢谢!

推荐答案

这是正确的方法:

const {
  propertyA,
  propertyA: {
    property1
  }
} = complicatedObject

如果您要访问propertyA和property1而不使用多个声明.

If you want to access both propertyA and property1 without using multiple declaration.

console.log(propertyA) // { property1: 1, property2: 2}
console.log(property1) // 1


但是如果我是你,我会做的就像


But if I were you, I would do just like:

const { propertyA } = complicatedObject
console.log(propertyA)
console.log(propertyA.property1)


或者,使用多个声明:


Or, using multiple declaration:

const { propertyA } = complicatedObject,
      { property1 } = propertyA
console.log(propertyA, property1)


实际上,您帖子的目的是质疑使用方式,例如:


Actually, the purpose of your post is to question to use like:

const { propertyA: { property1 } } = complicatedObject
console.log(propertyA, property1)

我会说,这是不可能的.因为,用冒号构造对象只是该属性的别名.例如.

And I would say, this is not possible. Because, constructuring object with colon just behaves an alias to the property. For eg.

const { propertyA: A } = complicatedObject
console.log(A) // works as if it is propertyA
console.log(propertyA) // won't work because propertyA is transformed to A

类似地

const { propertyA: { property1 } } = complicatedObject

propertyA转换为{ property1 },并且可以访问property1.

propertyA is transformed to { property1 } and can be accessed property1.

也是property1的别名,

const { propertyA: { property1: prop1 } } = complicatedObject
console.log(prop1)

这篇关于如何解构对象的属性和属性的属性. ES6 Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-18 16:35