简体   繁体   English

如何通过值(如果包含)获取键在数组中的索引?

[英]How do you get the index of a key in a array by and if value contains?

Here's my what I meant. 这就是我的意思。

var brands = [['brand: LV'], ['brand: Apple']]...

With this, I want to position(index) of say..Apple. 有了这个,我想定位诸如苹果的位置(索引)。 Manually, I can easily do 手动操作,我可以轻松完成

brands[1]

But this gets dynamically updated, therefor the index will be random. 但这会动态更新,因此索引将是随机的。

Use findIndex() or indexOf() . 使用findIndex()indexOf()

Example : brands.findIndex(doc => doc[0] === 'brand: Apple') . 示例: brands.findIndex(doc => doc[0] === 'brand: Apple')

Your format is a little inconvenient, normally you would have an array of objects not an array of strings like this, but at any rate you can still: 您的格式有点不方便,通常您会有一个对象数组而不是像这样的字符串数组,但是无论如何您仍然可以:

 let brands = [ ['brand: LV'],['brand: Apple']] let f = brands.findIndex(subarray => subarray.some(i => i.includes('Apple'))) console.log(f, brands[f]) 

Note that since you have these arrays it accounts for the possibility of one of them having more than one value. 请注意,由于您拥有这些数组,因此可以考虑其中之一具有多个值的可能性。 So consider: 因此请考虑:

 let brands = [['brand: LV'], ['brand: Sony', 'brand: Apple']] let f = brands.findIndex(subarray => subarray.some(i => i.includes('Apple'))) console.log(f, brands[f]) 
If you know each subarray will only have one value, you can just test for that: 如果您知道每个子数组只有一个值,则可以测试一下:

 let brands = [ ['brand: LV'],['brand: Apple']] let f = brands.findIndex(subarray => subarray[0].includes('Apple')) console.log(f, brands[f]) 

Since your data is an array of arrays, a simple includes or indexOf won't work on the top level, you need to test each element. 由于您的数据是一个数组数组,因此简单的includesindexOf不能在顶层使用,因此您需要测试每个元素。 Using findIndex allows you to apply a custom function to each element in turn: 使用findIndex允许您依次将自定义函数应用于每个元素:

 let brands = [ ['brand: LV'], ['brand: Apple'] ]; function findBrand(name) { let testValue = `brand: ${name}`; return brands.findIndex( elem => elem.includes(testValue) ); } console.log(findBrand('Apple')) 

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

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