长数组的对象解构解决方案? [英] Object destructuring solution for long arrays?
问题描述
看这段代码:
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];
这篇关于长数组的对象解构解决方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!