[英]Array has 5 objects and each object has an array property of another 5 objects. I'm trying to make function that finds the object with ID
First of all, this is the JSON file which is used - https://ddragon.leagueoflegends.com/cdn/9.14.1/data/en_US/runesReforged.json首先,这是使用的 JSON 文件 - https://ddragon.leagueoflegends.com/cdn/9.14.1/data/en_US/runesReforged.json
Currently I have this function that allows me to put a specific id as an argument and get one of the 5 main objects in that array:目前我有这个函数,它允许我将一个特定的 id 作为参数并获取该数组中的 5 个主要对象之一:
findSummonerRune: (state) => (id) => {
let rune = state.summonerRunes.find(rune => rune.id == id);
return rune
}
So findSummonerRune(8100)
returns the first object with "key": "Domination"
property.所以findSummonerRune(8100)
返回第一个具有"key": "Domination"
属性的对象。 However, if I try to find rune with id of 8112
, it doesn't work because that rune is a sub-rune which is found in the properties of rune with id of 8100
.但是,如果我尝试查找 id 为8112
符文,它不起作用,因为该符文是一个子符文,可在 id 为8100
的符文属性中找到。 More specifically, in the slots
property.更具体地说,在slots
属性中。
Now I understand why my function doesn't work, it's made to find which one of the main 5 objects has a property id == id, however, I'm just not sure how to also loop through their array property slots to look for the other runes as well.现在我明白为什么我的函数不起作用了,它是用来查找主要 5 个对象中的哪一个具有属性 id == id,但是,我只是不确定如何循环遍历它们的数组属性槽来查找其他符文也是如此。
personally, if you want to return the item from slots
, I'd flatten my list once upfront:就个人而言,如果您想从slots
返回该项目,我会预先将我的列表展平:
state.flattenedRunes = state.summonerRunes.reduce((acc, rune) =>
acc.concat([rune], rune.slots.reduce((a, r) => a.concat(r.runes), [])), []);
and I'd just search that list instead而我只是搜索该列表
if you want to actually return the main object that contains the item in its slots
, then do this to also check the sub arrays on your find.如果您想实际返回在其slots
中包含该项目的主要对象,则执行此操作以检查您的发现中的子数组。
let rune = state.summonerRunes.find(rune => rune.id == id || rune.slots.find(slot => slot.runes.find(r => r.id == id)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.