我有一个对象,需要在其中找到特定的项目索引号。以下是我的对象:
[
{
"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
}
]
例如,我需要找到Invert
属性具有值type
的项目的索引号。因此,在这种情况下,输出应为2
。我只需要搜索type
键的值。
答案 0 :(得分:9)
通过传递提供的 callback 函数作为参数,可以使用findIndex
方法。
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)
以下是该代码的简短摘要。
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'));
答案 2 :(得分:0)
您可以使用下划线或loadash(_)包。它具有对阵列操作的多种功能支持。
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)