JS Array Object same Item merge processing

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.