对象数组中多个属性的 IndexOf 方法

IndexOf Method for Multiple Properties in Object Array

在给定多个属性的情况下获取对象数组中对象索引的最佳方法是什么?

想象一下下面的示例数组:

var array = [
    {
        color: 'red',
        shape: 'square',
        weight: 200
    },
    {
        color: 'blue',
        shape: 'circle',
        weight: 300
    },
    {
        color: 'red',
        shape: 'circle',
        weight: 100
    }
];

现在我想要 indexOf color 属性 是 redshapecircle 的对象,在此示例中,将是 2.

理想情况下,函数将 return 对象的索引,当其属性的子集被给出时 {color: 'red', shape: 'circle'} 和 return -1 如果没有找到索引。

您可以使用映射数组方法实现此目的:

var array = [
{
    color: 'red',
    shape: 'square',
    weight: 200
},
{
    color: 'blue',
    shape: 'circle',
    weight: 300
},
{
    color: 'red',
    shape: 'circle',
    weight: 100
}
];
   
 var res = array.map(function(x,i){
    if( x.color == 'red')
    return i;
           
 })
//then you can filter out results to your needs
console.log(res.filter(function(x){return x != undefined}))

ES6中有数组方法findIndex:

let index = array.findIndex(
    element => element.color === 'red' && element.shape === 'circle'
);

在那之前,坚持简单的迭代:

var index = -1; // -1 if not found
for (var i = 0; i < array.length; ++i)
{
    var element = array[i];
    if (element.color === 'red' && element.shape === 'circle')
    {
        index = i;
        break;
    }
}

您可以使用地图并组合属性来执行此操作:

var index = array.map(function(o){return o.color + o.shape}).indexOf('red' + 'circle')