在javascript中解构嵌套对象|分解二级父对象和子对象 [英] Destructuring Nested objects in javascript | Destructure second level parent and child Objects

查看:223
本文介绍了在javascript中解构嵌套对象|分解二级父对象和子对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要解构并从该对象获取title,child,childTitle的值

I need to destructure and get values of title, child, childTitle from this object

const obj1 = {
   title : 'foo',
   child : {
               title2 : 'bar'
           }
   }

let {title, child} = obj1;
console.log(title)   //'foo'
console.log(child)   //{ title : 'bar' } 

// but couldn't get child object this way

let { title , child : { title2 } } = obj1;
console.log(title)   //'foo'
console.log(child)   //unDefined
console.log(title2)  //'bar'

如何获得子对象?

推荐答案

child: { title2 }只是在破坏child属性.如果要提取子属性本身,只需在语句中指定它即可:let { title, child, child: { title2 } } = obj1;

child: { title2 } is just destructuring the child property. If you want to pick up the child property itself simply specify it in the statement: let { title, child, child: { title2 } } = obj1;

const obj1 = {
  title: 'foo',
  child: {
    title2: 'bar'
  }
}

let { title, child, child: { title2 } } = obj1;

console.log(title);
console.log(child); 
console.log(title2);

这篇关于在javascript中解构嵌套对象|分解二级父对象和子对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆