繁体   English   中英

按值搜索对象数组并返回匹配的对象

[英]search array of objects by value and return matched object

我有一个对象数组:

[{
  "12": {"data": [{"thisID": "44"},{"thisID": "55"}],
       "settings": {"other":"other"}}
},{
  "15": {"data": [{"thisID": "66"},{"thisID": "77"}],
        "settings": {"other":"other"}}
}]

使用underscore.js我想访问thisID键为77对象。

我是这样做的,但我相信还有更好的方法吗?

var found = _.map(array, function (d) {
        return  _.findWhere(d.data, {thisID: "77"});
    })
    .filter(function(n){ return n != undefined })

console.log(found) //[{thisID:x, a:a, ....}]

首先,我认为如果要使用下划线,则应将其用于所有内容 -不应改回Javascript的内置.filter 我相信,如果存在下划线,它将遵循内置方法,否则它将替代其自己的实现

第二,由于数据的嵌套性质,您需要根据进一步过滤对象的值的data属性来过滤对象。 这说明_.values(obj)[0].data作为第一个参数传递给第二个filter调用。

最后,如果您确定只有一个具有所需thisID值的对象,则始终可以最后引用found[0] 因此,即使我正在提交的代码也可能有所改进,但我希望它可以为您指明正确的方向。 一个有益的练习可能是创建一个函数,该函数将所需的thisID作为参数,而不是对其进行硬编码。

var found = _.filter(array, function(obj) {
    var hasId77 = _.filter(_.values(obj)[0].data, function(data) {
        return data.thisID == 77
    });

    if (!_.isEmpty(hasId77)) {
        return obj;
    }
});

console.log(JSON.stringify(found));

输出:

[  
   {  
      "15":{  
         "data":[  
            {  
               "thisID":"66"
            },
            {  
               "thisID":"77"
            }
         ],
         "settings":{  
            "other":"other"
         }
      }
   }
]

这是您可以通过reduce实现的一种方法。 它与您的示例的长度相同,但是您的示例没有考虑一层嵌套。 假定最外面的对象只有一个键/值,如示例中的所有对象一样。

var test_array = [{
  "12": {"data": [{"thisID": "44"},{"thisID": "55"}],
         "settings": {"other":"other"}}
}, {
  "15": {"data": [{"thisID": "66"},{"thisID": "77"}],
         "settings": {"other":"other"}}
}];
var found = _.reduce(test_array, function(memo, inner_object) {
    var data = _.values(inner_object)[0].data
    return memo.concat(_.where(data, {thisID: "77"}));
}, []);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM