我有一些数据如下:
var items = [
{ "id" : 1,
"title" : "this",
"groups" : [
{"id" : 1,
"name" : "groupA"},
{"id" : 2,
"name" : "groupB"}
]
},
{ "id" : 2,
"title" : "that",
"groups" : [
{"id" : 1,
"name" : "groupA"},
{"id" : 3,
"name" : "groupC"}
]
},
{ "id" : 3,
"title" : "other",
"groups" : [
{"id" : 3,
"name" : "groupC"},
{"id" : 2,
"name" : "groupB"}
]
}]
我想基于组ID进行过滤,但我甚至无法访问它们 - item.group返回整个对象并执行任何其他操作(即item.groups.id)返回null或未定义的值
任何有关如何做到这一点的帮助都会很棒。基本上我想过滤数组以包含特定组中的所有项目。
由于
答案 0 :(得分:0)
试试这个:
map()
答案 1 :(得分:0)
使用:
Array.prototype.map
创建一个新数组,通过groups
键
Array.prototype.filter
仅保留具有正确id
。*需要像babel或打字稿这样的转录程序
OR
如果你想展平结构,那么可以使用Array.prototype.reduce
来组合数组。
以下代码有两个输出:
3
ID的群组中的项目。
const items = [{
"id": 1,
"title": "this",
"groups": [{
"id": 1,
"name": "groupA"
},
{
"id": 2,
"name": "groupB"
}
]
},
{
"id": 2,
"title": "that",
"groups": [{
"id": 1,
"name": "groupA"
},
{
"id": 3,
"name": "groupC"
}
]
},
{
"id": 3,
"title": "other",
"groups": [{
"id": 3,
"name": "groupC"
},
{
"id": 2,
"name": "groupB"
}
]
}
];
const filteredRemovingGroups = items.map(item => ({
...item,
groups: item.groups.filter(subItem => subItem.id === 3)
}));
const filterAndFlatten = items.map(item =>
item.groups.filter(subItem => subItem.id === 3)
).reduce((combinedArr, arr) => [...combinedArr, ...arr], [])
console.log('filteredRemovingGroups', filteredRemovingGroups);
console.log('filterAndFlatten', filterAndFlatten);

答案 2 :(得分:0)
你可以这样做
var items = [{
"id": 1,
"title": "this",
"groups": [{
"id": 1,
"name": "groupA"
}, {
"id": 2,
"name": "groupB"
}]
}, {
"id": 2,
"title": "that",
"groups": [{
"id": 1,
"name": "groupA"
}, {
"id": 3,
"name": "groupC"
}]
}, {
"id": 3,
"title": "other",
"groups": [{
"id": 3,
"name": "groupC"
}, {
"id": 2,
"name": "groupB"
}]
}]
// A filter function to filter out the matched value
function filterArray(array, val) {
return array.filter(function(elem) {
return elem.id === val; // filtering by Id
})
}
// first filtering the original items array, & will get the object where id is 1
var obj = filterArray(items, 1);
//the previous result will return an array,
//so doing obj[0] which will give the first index.
//obj[0].groups will be an array again
var filterGroup = filterArray(obj[0].groups,1) // will be an array which contains the matched group