1. Background:
var a = [
{
name:'张三,李四',
personId:'111,222',
id:'1'
},{
name:'王五',
personId:'333',
id:'2'
}
];
var b = [
{
name:'张三',
personId:'111',
id:'1'
},{
name:'李四',
personId:'222',
id:'1'
},{
name:'王五',
personId:'333',
id:'2'
},{
name:'王六',
personId:'444',
id:'3'
}
];
After the b array is updated, if you want to get a new a array, merge the name field and personId field of data with the same ID, and splice them with ',';
2. Think of the high-order function reduce
3. Code judgment logic
var brr = brr.concat(arr);
var obj = {};
var b = [];
b = brr.reduce(function(item,next){
if(obj[next.id]){
for(var k=0;k<item.length;k++){
if(item[k].id == next.id){
var flag = '0';
var crr = item[k].personId.split(',');
for(var i=0;i<crr.length;i++){
if(crr[i] == next.personId){
flag = '1';
}
}
if(flag == '0'){
item[k].name= item[k].name+','+next.name;
item[k].personId= item[k].personId+','+next.personId;
}
}
}
}else{
obj[next.id] = true && item.push(next);
}
return item;
},[]);
This not only fulfills the requirements, but also ensures that the data will not be spliced repeatedly.
That’s it, just record it like this, higher-order functions are delicious! ! ! ! ! ! ! ! ! ! ! !