返回具有相同密钥的字符。

huangapple go评论69阅读模式
英文:

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.someArray.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)

huangapple
  • 本文由 发表于 2023年2月10日 06:08:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75404948.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定