在不使用任何库的情况下如何实现?
我已经尝试过使用一些ES6函数,但是最终复制了数组中的某些项目.它应该返回唯一,尤其是当数组中没有子数组时
我有三个数组变量:
data1 =第一个数据
data2 =要与data1合并的变量
data3 =合并变量的结果
let data1 = [{
"document_id": 12264,"detail_info": [{
"id": 745,"lot_no": "X12345",},{
"id": 744,"lot_no": "Z12345",}
]
},{
"document_id": 12226,"detail_info": [{
"id": 738,"lot_no": "B12345",{
"id": 739,"lot_no": "C12345",{
"document_id": 12221,"detail_info": []
}
]
let data2 = [{
"document_id": 12264,"detail_info": [{
"id": 744,{
"id": 743,"lot_no": "L12345","detail_info": [{
"id": 739,}]
},{
"document_id": 12229,"detail_info": [{
"id": 741,"lot_no": "E12345",{
"document_id": 10095,"detail_info": []
}
]
//**This should be the result**
let data3=[
{
"document_id": 12264,"detail_info": [
{
"id": 745,{
"id": 744,{
"id": 743,}
]
},{
"document_id": 12226,"detail_info": [
{
"id": 738,{
"id": 739,{
"document_id": 12221,"detail_info": []
},{
"document_id": 12229,"detail_info": [
{
"id": 741,{
"document_id": 10095,"detail_info": []
}
]
最佳答案
首先将data1和data2连接到单个数组([… data1,… data2])中.
原文链接:https://www.f2er.com/js/531184.html然后使用Array.reduce()
生成一个字典,其键是在数组中找到的所有可能的document_id.
在reduce内部,当document_id的条目已经存在时,则必须将detail_info合并在一起.从现有条目和当前项创建一个包含所有detail_info的数组,并使用从detail_info.id生成的Set删除重复项,然后将此ID Set映射到相应的detail_info条目.
最后,将字典转换为带有Object.values()
的数组:
const data1 = [
{ "document_id": 12264,someData: 'hello',"detail_info": [{ "id": 745,"lot_no": "X12345" },{ "id": 744,"lot_no": "Z12345" }] },{ "document_id": 12226,"detail_info": [{ "id": 738,"lot_no": "B12345" },{ "id": 739,"lot_no": "C12345" }] },{ "document_id": 12221,"detail_info": [] }
];
const data2 = [
{ "document_id": 12264,"detail_info": [{ "id": 744,"lot_no": "Z12345" },{ "id": 743,"lot_no": "L12345" }] },"detail_info": [{ "id": 739,{ "document_id": 12229,"detail_info": [{ "id": 741,"lot_no": "E12345" }] },{ "document_id": 10095,"detail_info": [] }
];
const distinctById = arr => [...new Set(arr.map(({ id }) => id))]
.map(id => arr.find(info => info.id === id))
const data3 = Object.values([...data1,...data2].reduce((acc,x) => {
acc[x.document_id] = acc[x.document_id] || { ...x,detail_info: [] };
acc[x.document_id].detail_info = distinctById([...acc[x.document_id].detail_info,...x.detail_info]);
return acc;
},{}));
console.log(data3);
如果要按插入顺序使detail_info数组保持顺序,请执行以下操作:
const distinctById = arr => {
const uniqueIds = new Set(arr.map(({ id }) => id));
return arr.filter(({ id }) => uniqueIds.delete(id));
}
console.log(distinctById([{ id: 5 },{ id: 4 },{ id: 5 },{ id: 3 },{ id: 4 }]))