关于javascript:查找具有特定键的特定值的数组中对象的索引

Find index of object in array with specific value for specific key

本问题已经有最佳答案,请猛点这里访问。

我有一个对象,我需要找到一个特定的项目索引号。 以下是我的目标:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
[
  {
   "type":"Grayscale",
   "mode":"average"
  }, {
   "type":"Sepia"
  }, {
   "type":"Invert",
   "invert": true
  }, {
   "type":"Convolute",
   "opaque": false,
   "matrix": [1, 1, 1, 1, 0.7, -1, -1, -1, -1]
  }, {
   "type":"Convolute",
   "opaque": false,
   "matrix": [0, -1, 0, -1, 5, -1, 0, -1, 0]
  }, {
   "type":"Brownie"
  }, {
   "type":"Brightness",
   "brightness": 0.35
  }
]

例如,我需要找到type属性值Invert的项的索引号。 所以在这种情况下,输出应该是2。 我只需要搜索type键的值。


您可以使用findIndex方法,将提供的回调函数作为参数传递。

1
2
let arr = [ {"type":"Grayscale","mode":"average"}, {"type":"Sepia"}, {"type":"Invert","invert":true}, {"type":"Convolute","opaque":false,"matrix":[1,1,1,1,0.7,-1,-1,-1,-1]}, {"type":"Convolute","opaque":false,"matrix":[0,-1,0,-1,5,-1,0,-1,0]}, {"type":"Brownie"}, {"type":"Brightness","brightness":0.35} ], key = 'type';
console.log(arr.findIndex(elem => elem[key] == 'Invert'));


这是代码的简短代码段。

1
2
3
4
5
6
7
8
9
10
var sample = [{"type":"Grayscale","mode":"average"},{"type":"Sepia"},{"type":"Invert","invert":true},{"type":"Convolute","opaque":false,"matrix":[1,1,1,1,0.7,-1,-1,-1,-1]},{"type":"Convolute","opaque":false,"matrix":[0,-1,0,-1,5,-1,0,-1,0]},{"type":"Brownie"},{"type":"Brightness","brightness":0.35}]  

function findIndex(data, keyfield, value){
 
  return data.indexOf(data.find(function(el,index){
    return el[keyfield] === value;
  }));
}

console.log(findIndex(sample, 'type', 'Invert'));


你可以使用下划线或loadash(_)包。 它具有对阵列操作的多种功能支持。

1
2
3
4
5
6
7
8
9
10
11
12
13
const _ = require('lodash')

let your_array=  [
      {"type":"Grayscale","mode":"average"},
      {"type":"Sepia"},
      {"type":"Invert","invert":true},
      {"type":"Convolute","opaque":false,"matrix":[1,1,1,1,0.7,-1,-1,-1,-1]},
      {"type":"Convolute","opaque":false,"matrix":[0,-1,0,-1,5,-1,0,-1,0]},
      {"type":"Brownie"},
      {"type":"Brightness","brightness":0.35}
    ];
    let objectIndex = _.findIndex(your_array, each_element=> each_element.type =="Invert");
    alert(objectIndex)