首页 \ 问答 \ 对象分配的嵌套解构(Nested Destructuring on Object Assignments)

对象分配的嵌套解构(Nested Destructuring on Object Assignments)

使用ES6解构,他们可以在任务中解构嵌套对象吗?

这是一个快速的代码示例,以显示我的意思:

let node = {
  ItemTitle: 'Title',
  ItemId: 5,
  Menu: {Item: [{ItemId: 579}]
}

 // my attempts
  let {
      ItemId: id,
      ItemTitle: title, 
      Menu['Item']: subItems
    } = node

  let {
      ItemId: id,
      ItemTitle: title, 
      Menu.Item: subItems
    } = node

With ES6 destructuring, is their any way to destructure nested objects on assignment?

Here is a quick code example to show what I mean:

let node = {
  ItemTitle: 'Title',
  ItemId: 5,
  Menu: {Item: [{ItemId: 579}]
}

 // my attempts
  let {
      ItemId: id,
      ItemTitle: title, 
      Menu['Item']: subItems
    } = node

  let {
      ItemId: id,
      ItemTitle: title, 
      Menu.Item: subItems
    } = node

原文:https://stackoverflow.com/questions/40429117
更新时间:2020-10-16 21:10

最满意答案

对于嵌套级别,您可以重复相同的语法,如同对顶级进行解构:

根据您的评论编辑

我需要数组中的对象

let node = {
  ItemTitle: 'Title',
  ItemId: 5,
  Menu: {Item: [{ItemId: 579}]}
}

let {
  ItemId: id,       // extract `node.ItemId` into a variable called `id`
  ItemTitle: title, // extract `node.ItemTitle` into a variable called `title`
  Menu: {
    Item: [obj]     // extract `node.Menu.Item[0]` into a variable called obj
  }
} = node;

console.log('id =', id);
console.log('title =', title);
console.log('obj =', obj);

预编辑:在嵌套数组中提取对象的id。

let node = {
  ItemTitle: 'Title',
  ItemId: 5,
  Menu: {Item: [{ItemId: 579}]}
}

let {
  ItemId: id,           // extract `node.ItemId` into a variable called `id`
  ItemTitle: title,     // extract `node.ItemTitle` into a variable called `title`
  Menu: {
    Item: [{ 
      ItemId: subItemId // extract `node.Menu.Item[0].ItemId` into a variable called `subItemId`
    }]  
  }
} = node;

console.log('id =', id);
console.log('title =', title);
console.log('subItemId =', subItemId);


You can just repeat the same syntax for nested levels as with destructuring the top level:

EDIT based on your comment

I need the object within the array

let node = {
  ItemTitle: 'Title',
  ItemId: 5,
  Menu: {Item: [{ItemId: 579}]}
}

let {
  ItemId: id,       // extract `node.ItemId` into a variable called `id`
  ItemTitle: title, // extract `node.ItemTitle` into a variable called `title`
  Menu: {
    Item: [obj]     // extract `node.Menu.Item[0]` into a variable called obj
  }
} = node;

console.log('id =', id);
console.log('title =', title);
console.log('obj =', obj);

Pre-edit: Extracting the id of the object within the nested array.

let node = {
  ItemTitle: 'Title',
  ItemId: 5,
  Menu: {Item: [{ItemId: 579}]}
}

let {
  ItemId: id,           // extract `node.ItemId` into a variable called `id`
  ItemTitle: title,     // extract `node.ItemTitle` into a variable called `title`
  Menu: {
    Item: [{ 
      ItemId: subItemId // extract `node.Menu.Item[0].ItemId` into a variable called `subItemId`
    }]  
  }
} = node;

console.log('id =', id);
console.log('title =', title);
console.log('subItemId =', subItemId);

2016-11-04

相关问答

更多

对象解构:如何使用中间嵌套属性(object destructuring: how to use intermediate nested property)

我能想到的最接近的是: var { iWantThis, iWantThis: { andThis, andThisToo } } = x; 我以为我会使用let ,如果我使用的是ES6;) The closest I can come up with is: var { iWantThis, iWantThis: { andThis, andThisToo } } = x; Thought I'd use let instead, if I'm using ES6 ;)

JS嵌套对象中的解构对象(Destructuring Object in JS - Nested Object)

你能用这个吗? const {user} = xhrResponse.person || {}; 对于更新的用例,我想知道这是否可行? $q.all([ somePromise, someOtherPromise, getPersonPromise.then(res => (res.person || {}).user) ]).then(promises => [vm.promise1, vm.promise2, vm.user] = promises); Could you ju ...

将嵌套对象解构为函数参数(Destructuring nested objects as function parameters)

你可以这样做: const myFunc = ({event: {target: {name}}}) => { console.log(name) } myFunc({event: {target: {name: 'fred'}}}) .as-console-wrapper { max-height: 100% !important; top: 0; } 这是另一个实现,两个参数都有,但第二个完全是optionnal: const myFunc = ( {name: n ...

对象解构(Object Destructuring)

您可以使用三元运算符一次定义doc all来测试条件。 如果需要删除undefined属性,则可以通过reduce删除它们。 const { _id, name, bio, birth_date, photos, instagram, gender, jobs, schools } = element const myPhotos = photos.map(({ id }) => id) const insta = !instagram ? undefined : (() => { const ...

嵌套对象解构:重复声明“fontSize”(Nested object destructuring: Duplicate declaration “fontSize”)

您的解构声明基本上等同于 const fontSize = shevy.h1.fontSize, fontSize = shevy.p.fontSize; 这显然是无效的。 如果要对它们进行解构,则需要将它们分配给不同的变量。 我认为p的fontSize将被限定为p并且h1到h1以便styled.p知道使用哪个fontSize 。 不,没有这样的范围,它与嵌套对象没有任何关系。 解构目标中的所有变量都在同一范围内声明 - 它们只是普通的const变量,没有任何附加的命名空间。 请记住 ...

在Javascript中解构赋值的好处[关闭](Benefits of destructuring assignments in Javascript [closed])

好处是您不需要重复解构表达式。 当然,在你的例子中它几乎没有什么区别,因为你已经在metadata变量中得到了它。 但如果它是一个非常复杂的表达式,或其他东西,你可以保存一个额外的变量。 例如,比较此功能 function example(metadata) { var englishTitle = metadata.title, localeTitle = metadata.translations[0].title; …; // use englishTitl ...

通过解构为新对象赋值(Assign value to new object via destructuring)

用分号终止let obj = {}行解决了这个问题: let parameter = {id : 10, username : 'john'}; let obj = {}; ({id : obj.iduser, username : obj.user} = parameter); console.log(obj); Terminating the let obj = {} line with a semicolon solves this: let parameter = {id : 10, ...

嵌套对象解构[重复](Nested Object destructuring [duplicate])

const { user: { name: { first: firstName = 'firstName', last: lastName = 'lastName' } = {} } = {} } = data const { user: { name: { first: firstName = 'firstName', last: lastName = 'lastName' } = {} } = {} } = data

如何使用对象解构处理嵌套的默认参数?(How to handle nested default parameters with object destructuring?)

用于解构对象属性的通用模式是 { … , propertyName: target = defaultInitialiser, … } (当属性名称与目标变量标识符完全相同时,我们可以加入它们)。 但target不仅仅是变量,它可以是任何赋值目标 - 包括嵌套的解构表达式。 因此,对于您的情况(3),您希望在参数的顶层使用与(1)完全相同的方法 - 默认使用空对象初始化属性并对其部分进行解构: function fn3({foo = 'Foo', bar: {quux = 'Quux', cor ...

对象分配的嵌套解构(Nested Destructuring on Object Assignments)

对于嵌套级别,您可以重复相同的语法,如同对顶级进行解构: 根据您的评论编辑 我需要数组中的对象 let node = { ItemTitle: 'Title', ItemId: 5, Menu: {Item: [{ItemId: 579}]} } let { ItemId: id, // extract `node.ItemId` into a variable called `id` ItemTitle: title, // extract `n ...

相关文章

更多

最新问答

更多
  • 如何在CSS中进行自定义文本编辑并在学校项目中获取错误(How to do custom text editing in CSS and getting a error in a school project)
  • 获取列表中最长的元素(Get the longest element of a list)
  • Files.copy(Path,Path)是否创建目录?(Does Files.copy(Path,Path) create directories?)
  • 如何在ajax请求完成后1秒递归调用函数?(How to recursively call a function 1 second after an ajax request is done?)
  • 如何统计销售量,城市,商品使用情况的客户oracle(How to statistics sales, city, customer of goods use oracle)
  • 无法从命令行覆盖pom maven-surefire-plugin(Cannot overwrite pom maven-surefire-plugin from command line)
  • 根据Select2 4.0中的值应用css类(Applying css class according to value in Select2 4.0)
  • 使用Jackson(Polymorphic)进行反序列化时缺少字段(Missing field when deserializing using Jackson (Polymorphic))
  • 使用PHP的即时警报通知功能(Instant Alert notification feature using PHP)
  • 与以前的密码相比(Comparing with previous passwords)
  • 从现金流中获取特定行(Getting specific line from Cash Flow)
  • Citrix:无法使用MDKToolkit包装apk(Citrix: can't wrap apk using MDKToolkit)
  • 流星角色包的灵活性如何?(How flexible is meteor-roles package?)
  • 带有多个按钮的Google扩展程序(Google Extension with more than one button in the toolbar)
  • php setTimezone同时出现不同的结果(php setTimezone different result for the same time)
  • 搜索不使用jQuery调用json(Search not working using jQuery with call to json)
  • 如何打印文件的内容?(How do I print out the contents of a file? C++ File Stream)
  • Django自定义包含标签(Django Custom Inclusion Tags)
  • Java Jtree mouseEvent如果没有选择任何内容(Java Jtree mouseEvent if nothing is selected)
  • 通过哈希对象循环获取次数(Get number of times in loop over Hash object)
  • Python转义序列复杂输出(Python escape sequence complex output)
  • 将列表对象中的字符串转换为逗号分隔(Convert string in list objects to comma separated)
  • 如何限制特定字符在laravel 5.4中的字符串?(How to limit string in laravel 5.4 from specific char?)
  • 如何从浏览器调用appengine servlet(how to call appengine servlet from browser)
  • Excel条件格式更改整个行颜色(Excel conditional formatting to change entire row color)
  • 在JTable中显示数据库中的数据(Displaying data from database in JTable)
  • 在android中附加文件的问题(Issue on appending a file in android)
  • 在数组中输入值(Make in input value as in array)
  • Haml + ActionMailer - Rails?(Haml + ActionMailer - Rails?)
  • 在tomcat上部署的grails war没有连接到数据库(grails war deployed on tomcat is not connecting to database)