• JS实现JSON数组合并和去重


    var a=[{"id":"1001","name":"张三","age":"18","address":"北京市朝阳区","school":"朝阳区第二中学"},{"id":"1002","name":"李四","age":"15","address":"北京市海淀区","school":"海淀区第二中学"},{"id":"1003","name":"王五","age":"16","address":"北京市石景山区","school":"石景山区第二中学"}];
                var b=[{"id":"1004","name":"小毛","age":"18","address":"北京市朝阳区","school":"朝阳区第二中学"},{"id":"1003","name":"王五","age":"16","address":"北京市石景山区","school":"石景山区第二中学"}]
                var c = a.concat(b); //合并数组
                var temp = {}; //存放id
                var result = []; //新数组
                c.map((item,index) => {
                    if(!temp[item.id]){
                        result.push(item);
                        temp[item.id] = true;
                    }
                })
                document.getElementById('txt').innerHTML = JSON.stringify(result)
    有两个json数组demo1和demo2
    
    var demo1 = [{"id": 0, "name": "牛肉"},{"id": 1,"name": "羊肉"}];
    
    var demo2 = [{"id": 2, "name": "牛肉"},{"id": 3,"name": "鱼肉"},{ "id": 4,"name":"鸡肉"}];
    数组合并
    var totalDemo = demo1.concat(demo2);
    console.log(totalDemo); //[{"id": 0, "name": "牛肉"},{"id": 1,"name": "羊肉"},{"id": 2, "name": "牛肉"},{"id": 3,"name": "鱼肉"},{ "id": 4,"name":"鸡肉"}]
    数组合并用的是concat方法,它可以用于字符串之间的连接和数组之间的连接。
    
    数组去重
    上面已经得到合并的数组 totalDemo ,去掉name属性是一样的json对象
    
    var temp = {};   //用于name判断重复
    var result = [];  //最后的新数组
    
    totalDemo.map(function (item, index) {
        if(!temp[item.name]){
            result.push(item);
            temp[item.name] = true;
        }
    });
    
    console.log(result);//[{"id": 0, "name": "牛肉"},{"id": 1,"name": "羊肉"},{"id": 3,"name": "鱼肉"},{ "id": 4,"name":"鸡肉"}];
    map方法:按照原始数组元素顺序依次处理元素。可以在map方法里面输入console.log(item)打印看下,它会把数组中的对象依次打印出来。
  • 相关阅读:
    Mysql::Error: Commands out of sync; you can't run this command now: SHOW TABLES解决方案
    mysql安装失败Error Nr. 1045
    TermServDevices 报错【远程服务使用者必读】
    数据库出现“提取逻辑页失败”
    Ruby学习——数据库操作
    VS2008 安装失败
    Ubuntu Server 安装图解
    C#的Enum——枚举
    SQLServer2005数据库被置为“可疑”
    ROR之include、extend、send对module、class进行扩展
  • 原文地址:https://www.cnblogs.com/xianz666/p/13602908.html
Copyright © 2020-2023  润新知