两个数组根据相同id合并数组es6、原生js

对于两个数组,有些场景,我们需要根据id,把一个数组的某些属性,添加到另外一个数组.

        let arr1 = [
            {'id':1,'name':'高凯','age':10},
            {'id':2,'name':'张三','age':20},
            {'id':3,'name':'李四','age':30},
            {'id':4,'name':'赵武','age':10},
            {'id':5,'name':'王六','age':20},
        ];

        var arr2 = [
            {"id":1,"value":"111"},
            {"id":2,"value":"11111"},
            {"id":3,"value":"25462"},
            {"id":4,"value":"23131"},
            {"id":5,"value":"2315432"},
            {"id":6,"value":"333333"}
        ];

        var arr3 = [
            {"id":1,"name":"高凯","value":"111"},
            {"id":2,"name":"张三","value":"11111"},
            {"id":3,"name":"李四","value":"25462"},
            {"id":4,"name":"赵武","value":"23131"},
            {"id":5,"name":"王六","value":"2315432"},
            {"id":6,"value":"333333"}
        ];

        //对于数组arr1 和数组 arr2. 我们需要把数组arr1 里面的name属性以及值,根据id放在数组arr2 里面.也就数组arr3的形式

es6的map方法

        arr2.map((item2)=>{
            arr1.map((item1)=>{
                if(item2.id == item1.id){
                    let json = {
                        'name':item1.name
                    };
                    Object.assign(item2,json);
                    return item2;
                }
            })
        })
         console.log(arr2);

原生的js方法

        for(let i = 0; i< arr2.length;i++){
            for(let j = 0;j< arr1.length;j++){
                if(arr2[i].id == arr1[j].id){
                    arr2[i].name = arr1[j].name;
                }
            }
        }
        console.log(arr2);

博客地址:http://blog.gaokai.fun/

你可能感兴趣的:(两个数组根据相同id合并数组es6、原生js)