[英]Find Value in Nested Array
I'm trying to find a matching value within an array of objects. 我正在尝试在对象数组中找到匹配的值。
I'm using find
for the job, and that seems to work fine. 我正在使用find
来工作,这似乎工作正常。 But what if I need to assign more than one value to one of those keys? 但是,如果我需要为这些键之一分配多个值,该怎么办?
Here's the current code: 这是当前代码:
const snack = "strawberry";
const fruits = [
{ label: "yellowFruit", value: "banana" },
{ label: "purpleFruit", value: "grape" },
{ label: "redFruit", value: "apple" },
{ label: "greenFruit", value: "waltermelon" },
];
And here's how I'm finding my value: 这就是我寻找自己的价值的方式:
fruits.find(fruit => fruit.value === snack) || fruits[0]
I would actually need to associate two values to the label redFruit
without duplicating that label, as shown below, but then find
cannot do the job anymore. 我实际上需要将两个值与标签redFruit
而不必复制该标签,如下所示,但随后find
该标签redFruit
。
Something like this: 像这样:
const snack = "strawberry";
const fruits = [
{ label: "yellowFruit", value: "banana" },
{ label: "purpleFruit", value: "grape" },
{
label: "redFruit",
value: [
{ val: "apple" },
{ val: "strawberry" }
]
},
{ label: "greenFruit", value: "waltermelon" },
];
But finding strawberry
with the below code doesn't match: 但是用下面的代码查找strawberry
并不匹配:
fruits.find(fruit => fruit.value === snacks) || fruits[0]
Any help would be greatly appreciated. 任何帮助将不胜感激。
You have to use a different method based on the value
property type, if the value is an array then use Array#some
method to achieve the result. 您必须根据value
属性类型使用其他方法,如果值是数组,则使用Array#some
方法获得结果。
let res = fruits.find(({ value }) => Array.isArray(value) ? value.some(({ val }) => val === snacks) : value === snacks) || fruits[0]
const snacks = "strawberry"; const fruits = [{ label: "yellowFruit", value: "banana" }, { label: "purpleFruit", value: "grape" }, { label: "redFruit", value: [{ val: "apple" }, { val: "strawberry" } ] }, { label: "greenFruit", value: "waltermelon" }, ]; let res = fruits.find(({ value }) => Array.isArray(value) ? value.some(({ val }) => val === snacks) : value === snacks) || fruits[0] console.log(res);
Keep data simple: 保持数据简单:
const snack = "strawberry";
const fruits = [
{ label: "yellowFruit", value: "banana" },
{ label: "purpleFruit", value: "grape" },
{ label: "redFruit", value: "apple" },
{ label: "redFruit", value: "strawberry" },
{ label: "greenFruit", value: "waltermelon" },
];
... and your code will be simple too: ...,您的代码也将很简单:
const result = fruits.find(({ value }) => value === snack)
You can do so: 您可以这样做:
const snack = "strawberry"; const fruits = [{ label: "yellowFruit", value: "banana" }, { label: "purpleFruit", value: "grape" }, { label: "redFruit", value: [{ val: "apple" }, { val: "strawberry" } ] }, { label: "greenFruit", value: "waltermelon" }, ]; let itemExists = fruits.some(item => Array.isArray(item.value) ? item.value.some(subItem => subItem.val === snack) : item.value === snack); console.log(itemExists);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.