• 将一个JSON数组[{},{},{}]按一定规则合并到另一个JSON数组[{},{},{}]


    // 将一个JSON数组[{},{},{}]按一定规则合并到另一个JSON数组[{},{},{}]
    // Object.assign方法的第一个参数是目标对象,后面的参数都是源对象。
    var list1 = [{id:2,name:'aa'},{id:4,name:'bb'},{id:1,name:'cc'}];
    var list2 = [{id:2,age:10,sex:'男'},{id:1,age:18,sex:'男'},{id:4,age:16,sex:'女'}];
    var arr = [];
    var list = list1.map((item1)=> {
      arr = list2.filter((item2)=>{
        return item2.id == item1.id;
      });
      console.log(arr);
      console.log( Object.assign(item1,arr[0]) );
      return Object.assign(item1,arr[0] );
    });
    console.log(list1);// [ {id: 2,name: "aa",age: 10,sex: "男"},{id: 4,name: "bb",age: 16,sex: "女"},{id: 1,name: "cc",age: 18,sex: "男"}]
    console.log(list);// [ {id: 2,name: "aa",age: 10,sex: "男"},{id: 4,name: "bb",age: 16,sex: "女"},{id: 1,name: "cc",age: 18,sex: "男"}]

    // index索引一一对应
    var list3 = [{id:2,name:'aa'},{id:4,name:'bb'},{id:1,name:'cc'}];
    var list4 = [{id:2,age:10,sex:'男'},{id:4,age:16,sex:'女'},{id:1,age:18,sex:'男'}];
    var list5 = list3.map((item1,index) => {
      // 如果希望合并后返回一个新对象,可以改写上面函数,对一个空对象合并。
      console.log( Object.assign({},item1,list4[index]) );
      return Object.assign({},item1,list4[index] );
    });
    console.log(list3);//[{id:2,name:'aa'},{id:4,name:'bb'},{id:1,name:'cc'}]
    console.log(list5);// [ {id: 2,name: "aa",age: 10,sex: "男"},{id: 4,name: "bb",age: 16,sex: "女"},{id: 1,name: "cc",age: 18,sex: "男"}]

  • 相关阅读:
    适配器模式
    自己DIY word2010脚注和尾注没有的格式
    Linux单网卡,双IP,双网关配置,并搭建squid proxy上网
    about using gnuplot
    ReadDirectoryChangesW 函数 流沙
    Jquery easyui 异步树 流沙
    Overlapped I/O 学习 流沙
    jQuery.get(url,[data],[callback]) 流沙
    MsgWaitForMultipleObjectsEx用法 流沙
    Oracle smon_scn_time 表 说明
  • 原文地址:https://www.cnblogs.com/jianglibaizhi/p/10185490.html
Copyright © 2020-2023  润新知