In peacetime work will often encounter data processing, where the array merge processing will often encounter, the following is an array of the same method of merging:
1. First by the original array arr data,
2. Then create a map empty object and an dest empty array, by judging whether the map contains an item to determine whether the array dest add data,
3. Then judge the same item and the existing Dest array content comparison merge;
The code is as follows:
<script type= "Text/javascript" src= "Js/jquery.min.js" ></script>
<script>
$ (function () {
var arr = [
{"id": "1", "name": "Zhang San", "Value": "1245"},
{"id": "1", "name": "Zhang San", "Value": "1360"},
{"id": "2", "Name": "John Doe", "value": "1120"},
{"id": "2", "Name": "John Doe", "value": "1362"},
{"id": "2", "Name": "John Doe", "value": "1008"},
{"id": "3", "Name": "Harry", "Value": "1360"},
{"id": "4", "Name": "Zhao Liu", "Value": "1986"},
{"id": "4", "Name": "Zhao Liu", "value": "1240"}
];
var map = {},dest = [];
For (var i = 0; i < arr.length; i++) {
var ai = arr[i];
if (!map[ai.id]) {
Dest.push ({
Id:ai.id,
Name:ai.name,
Value:ai.value
});
map[ai.id] = AI;
}else{
For (var j = 0; J < Dest.length; J + +) {
var dj = dest[j];
if (dj.id = = ai.id) {
dj.value= (parsefloat (dj.value) + parsefloat (ai.value)). toString ();
Break ;
}
}
}
};
Console.log (dest);
})
</script>
JS Array Object same Item merge processing