IndexOf Method for Multiple Properties in Object Array

筅森魡賤 提交于 2021-02-16 05:19:13

问题


What's the best method to get the index of an object in an object array given multiple of it's properties?

Imagine the following example array:

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

Now I would like to have the indexOf the object which color property is red and shape is circle which, in this example, would be 2.

Ideally the function would return the index of the object when a subset of its properties is given like {color: 'red', shape: 'circle'} and return -1 if no index is found.


回答1:


In ES6, there is the array method findIndex:

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

Until then, stick to a plain iteration:

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:


You can do this with map and combining the properties:

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



回答3:


you could achieve this using map array method:

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


来源:https://stackoverflow.com/questions/32524117/indexof-method-for-multiple-properties-in-object-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!