Javascript:基于子对象值获取数组中的对象
如果我有这个对象:Javascript:基于子对象值获取数组中的对象,javascript,arrays,object,Javascript,Arrays,Object,如果我有这个对象: DropIds = [ { "studentId": 5, "dropboxItems": [ { "dropBoxId": 230, } ] }, { "studentId": 4, "dropboxItems": [ { "dropBoxId": 585, }, { "d
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,则结果为空
看来我的代码只会检查数组中的第一个对象
当存在多个dropBoxId时,如何抓取对象
谢谢 您需要检查数组中的所有项,而不仅仅是
0
索引,您可以使用
演示:这是因为您只测试第一个元素(零作为索引) 您必须在测试每个对象的元素内部循环
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;
});
var result=$.grep(DropIds,函数(e){
如果(!e.dropboxItems)返回false;
对于(var i=0;i
结合已经提供的答案,您可以充分利用映射和缩减来提取嵌套的
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];
};
您还需要循环查看
dropboxItems
的项目,而不是只查看第一个项目。您可以将内部.filter()
替换为(从而删除.length
)。在找到第一个匹配项之前,这将只选中复选框项。
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;
});
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];
};