英文:
return charachetrs with the same key door
问题
我有一个对象数组(角色),每个对象都有一个对象数组(钥匙),一个门可以被多个钥匙打开,正如您在这个示例中所看到的
const characters = [
{ id: "1", type: "water", keys: [{ name: "key_786", door: "XOPR" }] },
{ id: "2", type: "fire", keys: [{ name: "key_23", door: "JTHF" }] },
{ id: "3", type: "wind", keys: [{ name: "key_987", door: "XOPR" }] },
];
我想要找到所有具有可以打开特定门的钥匙的角色,例如,我想要返回所有keys.door === 'XOPR'
的角色,我该如何做?
我尝试过.filter
和.map
,但没有成功,可以帮助一下吗?我是React和JavaScript的新手。
英文:
I have an array of objects(characters) where each object has an array of objects(keys), a door can be opened by multiple keys as you can see in this example
const characters = [
{ id: "1", type: "water", keys: [{ name: "key_786", door: "XOPR" }] },
{ id: "2", type: "fire", keys: [{ name: "key_23", door: "JTHF" }] },
{ id: "3", type: "wind", keys: [{ name: "key_987", door: "XOPR" }] },
];
What I want is to find all the characters that have a key that can open one specific door, for example I want to return all characters with keys.door === 'XOPR'
how can I do it ?
I tried .filter .map but no luck, some help please ? I am new to react and javascript
答案1
得分: 2
你可以使用 Array.prototype.some 与 Array.prototype.filter:
const result = characters.filter(ch => ch.keys.some(key => key.door === 'DOOR_NAME'));
首先,你通过 filter
迭代 characters
数组,然后对于每个元素,你遍历它的 keys
属性,这是一个数组,对于其中的每个项,你检查是否 key.door === 'DOOR_NAME'
,然后返回该迭代的 character
。
英文:
you can use Array.prototype.some with Array.prototype.filter :
const result = characters.filter(ch => ch.keys.some(key => key.door === 'DOOR_NAME'));
First you filter
through characters
then for every one you loop through its keys
property which is an array and for every item of this latter you chack if key.door === 'DOOR_NAME'
so you return the character
for this itteration(of the filter loop)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论