长数组的对象解构解决方案?

编程入门 行业动态 更新时间:2024-10-23 06:29:04
本文介绍了长数组的对象解构解决方案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

看这段代码:

let lecture = { id: 2, title: "MyTitle", topics: [ { title: "John", age: 1 }, { title: "John2", age: 2 }, { title: "John3", age: 3 } ] }

我想提取数组中的主要title属性和第三个age(通过对象解构)

I want to extract the main title property and the third age in the array (via object destructuring)

我可以通过 :

let { title:lectureTitle , topics:[,,{age:thirdAge}]} = lecture; console.log(lectureTitle,thirdAge);//MyTitle 3

问题

但是如果数组有 100 个项目并且我想要第 99 个 age 怎么办?

But what if the array has 100 items and I want the 99'th age ?

那我该怎么做呢?对象解构是否为此提供了解决方案?

How would then I do it ? Does object destructuring offer a solution for that?

推荐答案

但是如果数组有 100 个项目并且我想要第 99 个年龄怎么办?

But what if the array has 100 items and I want the 99'th age ?

数组是对象,所以这样做:

Arrays are objects, so this will do:

let {title: lectureTitle, topics: {98: {age: thirdAge}}} = lecture;

注意 然而,[...] 类型的解构适用于任何可迭代对象,而 {...} 仅适用于对象(以及数组).要使上述解决方案适用于任意可迭代对象,您必须展开可迭代对象并将其用数组包装.

Note however that the [...] type of destructuring works with any iterable, whereas {...} only works with objects (and therefore arrays). For the above solution to work with arbitrary iterables you will have to spread the iterable and wrap it with an array.

let {title: lectureTitle, topics: {98: {age: thirdAge}}} = [...lecture];

更多推荐

长数组的对象解构解决方案?

本文发布于:2023-11-29 21:53:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647730.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   对象   解决方案

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!