1

Suppose I have an array of nested objects:

 this_menu = [{food_name: 'hamburger', food_attr: ['big', 'yummy', 'cheap']}, {food_name: 'sushi', food_attr: ['healthy', 'expensive', 'yummy']}, {food_name: 'tacos', food_attr: ['yummy', 'cheap', 'small']}]

If I want to find the the nested object that contains 'sushi', I could simply call this_array[1] by index. But lets say, I want to find it strictly by the key - food_name's value. I want to do this without using a for loop if possible and in a single line if it can be done. I basically want to return the object: {food_name: 'sushi', food_attr: ['healthy', 'expensive', 'yummy']}. I tried the following, but I think the syntax is wrong (throws a syntax error). Any suggestions on getting this to work:

tonights_dinner = this_menu.map((x) => if(x.food_name == `sushi') { return x});  
gwydion93
  • 1,681
  • 3
  • 28
  • 59
  • 2
    you can use find. but even with find it uses a loop anyway. `this_menu.find(({food_name}) => food_name==='sushi')` https://stackoverflow.com/questions/12462318/find-a-value-in-an-array-of-objects-in-javascript – cmgchess Apr 05 '23 at 12:49
  • 1
    btw the map also does a loop – cmgchess Apr 05 '23 at 12:52
  • Q: why is it necessary to be all on one line? – Andy Apr 05 '23 at 12:57
  • Yeah, find looks like a viable solution. In regards to the loop, what I wanted to avoid was a multi-liner `for` loop; sorry should have been more clear. – gwydion93 Apr 05 '23 at 13:00

1 Answers1

2

If you are sure there will be exactly one hit, use .find()

This might be the case if you know the "sushi" text has actually been picked off that menu itself, and you have pre-arranged for there to be no duplicate food_names.

const this_menu = [{
  food_name: 'hamburger',
  food_attr: ['big', 'yummy', 'cheap']
}, {
  food_name: 'sushi',
  food_attr: ['healthy', 'expensive', 'yummy']
}, {
  food_name: 'tacos',
  food_attr: ['yummy', 'cheap', 'small']
}]

const result = this_menu.find(item => item.food_name === "sushi")

console.log(result)

If you are unsure whether there will be 0, 1 or more hits, use .filter()

This is a more general situation. In this case you will want to know the number of hits, as well as have a list of hits.

const this_menu = [{
  food_name: 'hamburger',
  food_attr: ['big', 'yummy', 'cheap']
}, {
  food_name: 'sushi',
  food_attr: ['healthy', 'expensive', 'yummy']
}, {
  food_name: 'tacos',
  food_attr: ['yummy', 'cheap', 'small']
}]

const results = this_menu.filter(item => item.food_name === "sushi")

console.log(results.length)
console.log(results)
ProfDFrancis
  • 8,816
  • 1
  • 17
  • 26