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. 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.
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:
fruits.find(fruit => fruit.value === snacks) || fruits[0]
Any help would be greatly appreciated.
snacksis an object. how do you get the value from it?fruitsto match the value ofsnack. Thanks for your help