zoukankan      html  css  js  c++  java
  • 将一个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: "男"}]

  • 相关阅读:
    JSOI2015 总结
    JSOI2014 总结
    JSOI2010/2011 总结
    1.13 考试总结
    1.15 考试总结
    [SDOI2015]寻宝游戏
    [教程]视频网课如何打开倍速纵享丝滑
    对机器学习的一些理解【学术篇】
    angular JS 路由功能
    理解 $scope
  • 原文地址:https://www.cnblogs.com/jianglibaizhi/p/10185490.html
Copyright © 2011-2022 走看看