0

Lets say I have an array of objects:

inventory = [{name:'milk',price:4},{name:'apple',price:2}]

How could I reference the entire object that contains inventory.name = 'milk' or inventory.price = 4?

I need to reference it in order to return its index inside of the outer array.

Riley Hughes
  • 1,344
  • 2
  • 12
  • 22
  • Possible duplicate of [Javascript: How to filter object array based on attributes?](https://stackoverflow.com/questions/2722159/javascript-how-to-filter-object-array-based-on-attributes) – S. Walker Oct 24 '17 at 22:43

2 Answers2

3

There are several ways, but the first is:

const obj = inventory.find(object => object.name === "milk" || object.price === 4)

or you can use findIndex

P Varga
  • 19,174
  • 12
  • 70
  • 108
stevenlacerda
  • 1,187
  • 2
  • 9
  • 21
2

Seems like you are looking for Array#findIndex:

const index = inventory.findIndex(item => item.name === 'milk');

Or use Array#find if you want the actual object.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143