[英]How to loop through an array containing objects of objects
This is my array: 这是我的阵列:
[{
name: "Test",
skills: {
agile: true,
good: true
}
},
{
name: "Test 2",
skills: {
agile: false,
good: false
}
}]
I need to find the last element (his index) who has the skill good set to true. 我需要找到技能良好设置为真的最后一个元素(他的索引)。 The only way I know to fix this is to use a for/if combination.
我知道解决这个问题的唯一方法是使用for / if组合。 Is there any other faster/optimal way to do it ?
还有其他更快/最佳的方法吗?
Use filter: 使用过滤器:
const goodSkills = myArray.filter(x => x.skills.good)
Then get the last item: 然后得到最后一项:
goodSkills[goodSkills.length - 1]
Or if you only need the index, and we treat name
as a unique key: 或者,如果您只需要索引,我们将
name
视为唯一键:
const lastGoodIndex = myArray.findIndex(x => x.name === goodSkills[goodSkills.length - 1].name)
You can then use lastGoodIndex
for whatever nefarious purpose you have in mind. 然后,您可以将
lastGoodIndex
用于您lastGoodIndex
的任何恶意目的。
Alternatively if name
is not a unique key, I suggest just using forEach
: 或者,如果
name
不是唯一键,我建议只使用forEach
:
let lastGoodIndex;
myArray.forEach((x, i) => lastGoodIndex = x.skills.good ? i : lastGoodIndex);
console.log(lastGoodIndex);
The fastest way is to us a for loop: 最快的方法是给我们一个for循环:
var arr = [{ name: "Test", skills: { agile: true, good: true } }, { name: "Test 2", skills: { agile: false, good: false }, }] function findLastGoodIndex(arr) { for (let i = arr.length - 1; i >= 0; i--) { if (arr[i].skills.good) { return i; } } } console.log(findLastGoodIndex(arr));
Or if the list isn't that large you can combine reverse
with findIndex
: 或者如果列表不是那么大,你可以将
reverse
与findIndex
结合起来:
arr.reverse().findIndex(x => x.skills.good));
You can do it in 3 rows: 你可以在3行中完成:
var arr = [ { name: "Test", skills: { agile: true, good: true } }, { name: "Test 2", skills: { agile: false, good: false }, } ] var lastIndex; arr.forEach(function(item, i) { if(item.skills.good) lastIndex = i; }) console.log(lastIndex);
If you want the index
of last element that has good = true
your best option is to use for/if
(perhaps going backwards, ie i--
if you can guess where can you expect the good
item?). 如果你想在
index
有最后一个元素的good = true
你最好的选择是使用for/if
(可能是倒退,也就是i--
如果你能猜到你在哪里可以预期的good
项目吗?)。
filter
will find the item(s) too, and it also has index
property, but generally it's slower than for/if. filter
也会找到项目,它也有index
属性,但通常比/ if慢。
forEach
will also generally be slower than for/if
. forEach
通常也比for/if
慢。
edit:styling. 编辑:造型。
Since you need to search the last value, you should search in descending order. 由于您需要搜索最后一个值,因此您应该按降序搜索。 This would prevent any unnecessary iterations.
这可以防止任何不必要的迭代。
var data = [{ name: "Test", skills: { agile: true, good: true } }, { name: "Test 2", skills: { agile: false, good: false } } ]; var i = data.length; var result = null; while (i--) { if (data[i].skills.good) { result = i; break; } } console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.