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.
There are several ways, but the first is:
const obj = inventory.find(object => object.name === "milk" || object.price === 4)
or you can use findIndex
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.