我正在尝试在对象数组中查找匹配的值。
我正在使用 find
来完成这项工作,这似乎工作正常。但是,如果我需要为其中一个键分配多个值怎么办?
这是当前代码:
const snack = "strawberry";
const fruits = [
{ label: "yellowFruit", value: "banana" },
{ label: "purpleFruit", value: "grape" },
{ label: "redFruit", value: "apple" },
{ label: "greenFruit", value: "waltermelon" },
];
这就是我如何找到自己的值(value):
fruits.find(fruit => fruit.value === snack) || fruits[0]
实际上,我需要将两个值与标签 redFruit
相关联,而不复制该标签,如下所示,但 find
无法再完成这项工作。
类似这样的事情:
const snack = "strawberry";
const fruits = [
{ label: "yellowFruit", value: "banana" },
{ label: "purpleFruit", value: "grape" },
{
label: "redFruit",
value: [
{ val: "apple" },
{ val: "strawberry" }
]
},
{ label: "greenFruit", value: "waltermelon" },
];
但是使用以下代码查找 strawberry
不匹配:
fruits.find(fruit => fruit.value === snacks) || fruits[0]
任何帮助将不胜感激。
最佳答案
您必须根据 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);
关于javascript - 在嵌套数组中查找值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55327320/