当前位置:网站首页>JS implements JSON array merging and de duplication

JS implements JSON array merging and de duplication

2022-06-09 15:09:00 Don't stare at my name

There are two json Array demo1 and demo2

var demo1 = [{"id": 0, "name": " beef "},{"id": 1,"name": " mutton "}];

var demo2 = [{"id": 2, "name": " beef "},{"id": 3,"name": " Fish "},{ "id": 4,"name":" chicken "}];

Array merge

var totalDemo = demo1.concat(demo2);
console.log(totalDemo); //[{"id": 0, "name": " beef "},{"id": 1,"name": " mutton "},{"id": 2, "name": " beef "},{"id": 3,"name": " Fish "},{ "id": 4,"name":" chicken "}]

Array merging uses concat Method , It can be used to connect strings and arrays .

Array weight removal

The merged array has been obtained above totalDemo , Get rid of name The attributes are the same json object

var temp = {};   // be used for name Judgment repeats 
var result = [];  // Last new array 

totalDemo.map(function (item, index) {
    if(!temp[item.name]){
        result.push(item);
        temp[item.name] = true;
    }
});

console.log(result);//[{"id": 0, "name": " beef "},{"id": 1,"name": " mutton "},{"id": 3,"name": " Fish "},{ "id": 4,"name":" chicken "}];

JSON Array de duplication uses the attribute name of the object to make judgments , Then get the new array , Is the array after de duplication .

JSON Array de duplication method encapsulation

const arr = [{"id": 0, "name": " beef "},{"id": 1,"name": " mutton "},{"id": 2, "name": " beef "},{"id": 3,"name": " Fish "},{ "id": 4,"name":" chicken "}]

/**
 * JSON Array weight removal 
 * @params {Array} arr  Incoming JSON Array 
 * @param {String} attrName  According to which attribute name to duplicate 
 * @return {Array}  Returns a new array after de duplication 
 * */
function delRepeatJson(arr = [], attrName = '') {
    var temp = {}; // be used for name Judgment repeats 
    var result = []; // Last new array 

    arr.forEach(function (item, index) {
        if (!temp[item[attrName]]) {
            result.push(item);
            temp[item[attrName]] = true;
        }
    });
    return result;
}

console.log(delRepeatJson(arr, 'name')); // [{"id":0,"name":" beef "},{"id":1,"name":" mutton "},{"id":3,"name":" Fish "},{"id":4,"name":" chicken "}]
原网站

版权声明
本文为[Don't stare at my name]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206091429525424.html