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

时间:2015-09-11 12:59:35

标签: javascript arrays javascript-objects indexof

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

想象一下以下示例数组:

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

现在我希望indexOf color属性为redshapecircle的{​​{1}}对象,在此示例中为2 {color: 'red', shape: 'circle'}

理想情况下,当给定其属性的子集(如-1)时,函数将返回对象的索引,如果未找到索引则返回{ "resource_uri": "https://www.eventbriteapi.com/v3/orders/454268667/", "id": "454268667", "changed": "2015-09-11T09:34:03Z", "created": "2015-09-11T09:34:02Z", "costs": { "payment_fee": { "currency": "USD", "display": "$0.00", "value": 0 }, "gross": { "currency": "USD", "display": "$0.00", "value": 0 }, "eventbrite_fee": { "currency": "USD", "display": "$0.00", "value": 0 }, "tax": { "currency": "USD", "display": "$0.00", "value": 0 }, "base_price": { "currency": "USD", "display": "$0.00", "value": 0 } }, "name": "Breen Ho", "first_name": "Breen", "last_name": "Ho", "email": "breenXXX@gmail.com", "status": "placed", "time_remaining": null, "event_id": "18568926158" }

3 个答案:

答案 0 :(得分:2)

在ES6中,有数组方法findIndex

 "filter": {
    "bool": {
      "must": [{
        "query": {
          "match": {
            "_all": {
              "query": "cardio new york"
            }
          }
        }
      }, {
        "exists": {
          "fields": [
            "venue",
            "geo_location"
          ]
        }
      }]
    }
  }

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

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

答案 1 :(得分: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}))

答案 2 :(得分:1)

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

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