简体   繁体   English

如何通过JS中的内部键引用Obj

[英]How to reference an Obj by a key inside of it in JS

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? 我如何才能引用包含清单。名称=“牛奶”或清单。价格= 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 或者您可以使用findIndex

Seems like you are looking for Array#findIndex : 似乎您正在寻找Array#findIndex

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

Or use Array#find if you want the actual object. 或者,如果需要实际对象,请使用Array#find

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM