Javascript:根据子对象值在数组中抓取对象

时间:2015-01-16 22:37:45

标签: javascript arrays object

如果我有这个对象:

DropIds = [
  {
    "studentId": 5,
    "dropboxItems": [
        {
            "dropBoxId": 230,
        }
    ]
  },
  {
    "studentId": 4,
    "dropboxItems": [
        {
            "dropBoxId": 585,
        },
        {
            "dropBoxId": 586,
        }
    ]
  }
]

我尝试运行此代码:

var result = $.grep(DropIds, function(e){
    return e.dropboxItems[0].dropBoxId == 585;
});

它将返回一个结果,但是如果我将它从585更改为586,则结果为空。

http://jsfiddle.net/tdb70f50/1/

所以看起来我的代码只会检查数组中的第一个对象。

当有多个dropBoxId时,如何抓取对象?

谢谢!

3 个答案:

答案 0 :(得分:3)

您需要检查数组中的所有项目,而不仅仅是0索引,您可以使用Array.prototype.filter

var result = DropIds.filter(function(item) {
    return item.dropboxItems.filter(function(box) {
        return box.dropBoxId == 586
    }).length
});

演示:http://jsfiddle.net/56h7daod/

答案 1 :(得分:0)

那是因为你只测试第一个元素(零作为索引);

return e.dropboxItems[0].dropBoxId == 585;

你必须循环测试每个对象的元素;

var result = $.grep(DropIds, function(e){
    if(!e.dropboxItems) return false;

    for(var i = 0; i < e.dropboxItems.length; i++) {
        if(e.dropboxItems[i].dropBoxId == 586) return true
    }

    return false;
});

http://jsfiddle.net/tdb70f50/2/

答案 2 :(得分:0)

结合已经提供的答案,您可以充分利用映射和缩小来提取嵌套dropBoxItems的数组,然后搜索给定的dropBoxId,即:

function getByDropBoxId(id, dropId) {
  return dropId
    // Pluck the nested arrays into a 2d array
    .map(function (dropId) {
      return dropId.dropboxItems;
    })
    // flatten / reduce them to a single array.
    .reduce(function (soFar, dropBoxItems) {
      return soFar.concat(dropBoxItems);
    }, [])
    // filter out the ones you are looking for and return the first.
    .filter(function(dropBoxItem) {
      return dropBoxItem.dropBoxId === id; 
    })[0];
};