Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 按值搜索对象数组并返回匹配的对象_Javascript_Arrays_Object_Underscore.js - Fatal编程技术网

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

Javascript 按值搜索对象数组并返回匹配的对象,javascript,arrays,object,underscore.js,Javascript,Arrays,Object,Underscore.js,我有一个对象数组: [{ "12": {"data": [{"thisID": "44"},{"thisID": "55"}], "settings": {"other":"other"}} },{ "15": {"data": [{"thisID": "66"},{"thisID": "77"}], "settings": {"other":"other"}} }] 我想使用下划线.js访问thisID键为77的对象 我是这样做的,但我相信还有更好的方法

我有一个对象数组:

[{
  "12": {"data": [{"thisID": "44"},{"thisID": "55"}],
       "settings": {"other":"other"}}
},{
  "15": {"data": [{"thisID": "66"},{"thisID": "77"}],
        "settings": {"other":"other"}}
}]
我想使用下划线.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
。我相信下划线将遵从内置方法(如果它存在的话),否则它将替代它自己的实现

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

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

我不确定,但是数据的格式正确吗?你是对的,数据格式不好。现在应该没问题了,我想说,如果你的代码有效,“但是(你)相信有更好的方法”,这应该在codereview.stackexchange上,但是我运行了你的代码,它为我返回了一个空数组。是的,我想你没有考虑嵌套层。如果你将
d.data
更改为
\u.values(d)[0].data
然后它就工作了。