如何提取高度嵌套的对象的指定属性

有时候会遇到一些嵌套程度非常深的对象

const store={
    
    
goods:{
    
    
water:{
    
    
drinks:'wahaha'
}
//vegetable:'spinach'
}
}

此时的drinks嵌套4层,此时如果仍然尝试老方法提取:

const {
    
    drinks} = store

发现并不奏效,因为store对象本身并没有drinks这个属性,因为drinks位于第四层,因此想要把drinks提取出来,一种比较低级的做法:

const {
    
    goods} = store
const {
    
    water} = goods
const {
    
    drinks} = water 
console.log(drinks)  //wahaha

但是还有一种比较标准的做法,可以解决这个问题:

const {
    
    goods:{
    
    water:{
    
    drinks}}} = store

console.log(drinks)  //wahaha 

结论:

可以在结构出来的变量名右侧,通过冒号+{目标属性名}这种形式,进一步结构它,一直结构到拿到目标为止

猜你喜欢

转载自blog.csdn.net/weixin_47389477/article/details/142531145