0

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.

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.