<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
</body>
<script>
// js数组对象相同值相加,不同添加
var arr = [{id:1,name:'aaa'},{id:1,name:'bbb'},{id:1,name:'bbb'},{id:2,name:"ccc"},{id:3,name:'bbb2'},{id:3,name:'bbb'},,{id:2,name:"c2cc"},,{id:555,name:"ccc"}]
function mergeArr(arr){
var newArr=[];
arr.forEach(item=>{
var dataItem =item
if(newArr.length>0){
var filterValue = newArr.filter(v=>{
return v.id == dataItem.id
})
if(filterValue.length>0){
newArr.forEach(n=>{
if( n.id ==filterValue[0].id){
n.name = filterValue[0].name +dataItem.name
}
})
}else{
newArr.push(dataItem)
}
}else{
newArr.push(dataItem)
}
})
return newArr
}
console.log(mergeArr(arr))
</script>
</html>
js数组对象的相同值相加合并
最新推荐文章于 2024-05-27 16:22:10 发布