【问题标题】:IndexOf Method for Multiple Properties in Object Array对象数组中多个属性的IndexOf方法
【发布时间】:2015-12-08 01:16:45
【问题描述】:

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

想象以下示例数组:

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

现在我想要indexOf 的对象,其color 属性为redshapecircle,在本例中为2

理想情况下,当对象的属性子集如{color: 'red', shape: 'circle'} 给出时,该函数将返回对象的索引,如果未找到索引,则返回-1

【问题讨论】:

  • @JoelEtherton 我尝试的是循环数组,然后循环遍历属性,但我被卡住的部分是只获取与这两个值匹配的项目的索引。 IndexOf 只是 color redshape circle 不同。

标签: javascript arrays javascript-objects indexof


【解决方案1】:

在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;
    }
}

【讨论】:

    【解决方案2】:

    您可以使用地图并结合属性来做到这一点:

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

    【讨论】:

    • 很好,直到你有一个名为 redc 的颜色和一个名为 ircle 的形状;)。
    【解决方案3】:

    您可以使用地图数组方法实现此目的:

    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}))

    【讨论】:

      猜你喜欢
      • 2012-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-11
      • 1970-01-01
      相关资源
      最近更新 更多