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

Javascript: grab object in array based on subobject value

本文关键字:对象 抓取 数组 Javascript      更新时间:2023-09-26

如果我有这个对象:

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 时,如何抓取对象?

谢谢!

您需要检查数组中的所有项目,而不仅仅是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/

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

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/

结合

已经提供的答案,您可以充分利用映射和归约来提取嵌套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];
};