Javascript 如何将JSON对象从JSON对象数组中分组?
下面是一个JSON对象数组,其中包含我希望按pull unique分组的数组值:Javascript 如何将JSON对象从JSON对象数组中分组?,javascript,node.js,lodash,Javascript,Node.js,Lodash,下面是一个JSON对象数组,其中包含我希望按pull unique分组的数组值: let myArray = [ { "_id": "1", "subdata": [ { "subid": "11", "name": "A" }, { "subid": "12",
let myArray = [
{
"_id": "1",
"subdata": [
{
"subid": "11",
"name": "A"
},
{
"subid": "12",
"name": "B"
}
]
},
{
"_id": "2",
"subdata": [
{
"subid": "12",
"name": "B"
},
{
"subid": "33",
"name": "E"
}
]
}
]
最后,我需要得到:
[
{
"subid": "11",
"name": "A"
},
{
"subid": "12",
"name": "B"
},
{
"subid": "33",
"name": "E"
}
]
我尝试过lodash,但没有成功:
let newArray = lodash.uniqBy(lodash.concat(myArray, 'subdata.subid'), '_id');
当然,我可以逐个扫描每个数组元素,但我认为使用lodash可以很容易地做到这一点,使用u.flatMap获取所有子数据项的数组,然后使用u.uniqueBy with subid:
constmyarray=[{subid:1,子数据:[{subid:11,name:A},{subid:12,name:B}]},{subid:2,子数据:[{subid:12,name:B},{subid:33,name:E}];
const result=qby_qby.flatMapmyArray,'subdata','subid';
console.logresult;