Rob Welan
Rob Welan

Reputation: 2210

How to find a value by searching for a string within an array within an object

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

Answers (3)

Suren Srapyan
Suren Srapyan

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

6502
6502

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 types (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

Nina Scholz
Nina Scholz

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

Related Questions