Reputation: 2210
I have the following object:
data = [
{
type: "fruit",
basket: ["apple", "pear", "orange"]
},
{
type: "vegetable",
basket: ["carrot", "potato"]
}
];
I wish to search the data for 'potato' and have returned 'vegetable'. I am hoping to use filter or map, but I'm struggling with the syntax. Vanilla javascript please.
Upvotes: 0
Views: 55
Reputation: 68635
Use Array#find function to iterate over each object and using Array#some or Array#includes to iterate over each basket and check if there is an item with name potato
.
const data = [
{
type: "fruit",
basket: ["apple", "pear", "orange"]
},
{
type: "vegetable",
basket: ["carrot", "potato"]
}
];
const itemWithSome = data.find(item => item.basket.some(i => i === 'potato'));
console.log(itemWithSome.type);
const itemWithIncludes = data.find(item => item.basket.includes('potato'));
console.log(itemWithIncludes.type);
Upvotes: 0
Reputation: 114461
A solution is
var res = data.map(
x => x.basket.indexOf("potato") === -1 ? undefined : x.type
).filter(x => x !== undefined);
res
will be a list of all matching type
s (there can be more than one if the same value is contained multiple times. You can use res[0]
if you're sure the values are unique and in that case you'll get either the type
value or undefined
when it's not present.
Upvotes: 1
Reputation: 386550
You could use Array#find
with Array#includes
.
var data = [{ type: "fruit", basket: ["apple", "pear", "orange"] }, { type: "vegetable", basket: ["carrot", "potato"] }],
find = 'potato';
console.log(data.find(o => o.basket.includes(find)).type);
Upvotes: 0