【问题标题】:search array of objects by value and return matched object按值搜索对象数组并返回匹配的对象
【发布时间】:2015-07-06 08:46:20
【问题描述】:

我有一个对象数组:

[{
  "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, ....}]

【问题讨论】:

  • 我不确定,但数据格式是否正确?
  • 你说得对,数据格式不好。现在应该可以了
  • 我想说的是,如果您的代码有效“但(您)相信有更好的方法”,这属于 codereview.stackexchange,但我运行了您的代码,它返回一个空数组对我来说
  • 是的,我认为您没有考虑到嵌套层。
  • 如果您将d.data 更改为_.values(d)[0].data,那么它可以工作。

标签: javascript arrays object underscore.js


【解决方案1】:

首先,我认为如果你要使用下划线,你应该将它用于everything——你不应该改回Javascript的内置.filter。我相信下划线将遵循内置方法,如果它存在,否则它将替换它自己的实现

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

最后,如果您确定只有一个对象具有所需的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"
         }
      }
   }
]

【讨论】:

    【解决方案2】:

    这是一种您可以使用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"}));
    }, []);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-16
      • 1970-01-01
      • 2021-09-25
      • 1970-01-01
      相关资源
      最近更新 更多