首页 > js如何匹配两个对象数组!不要嵌套循环

js如何匹配两个对象数组!不要嵌套循环

var arr1 = [{id:1,name:"a",y:true},{id:2,name:"b",y:true},{id:3,name:"c",y:true},{id:4,name:"d",y:true},{id:5,name:"e",y:true}];
var arr2 = [{id:1,name:"a",y:true},{id:2,name:"b",y:true}];

怎么用arr2匹配arr1,如果arr1中某项的id等于arr2某项的id,就给arr1中相应相等的项的y改为false;


将数组arr1转为对象(其实是个map),然后直接查找就行了。

var mapOfArr1 = {};
arr1.forEach(function(e){
    mapOfArr1[e.id] = e;
});
arr2.forEach(function(e){
    mapOfArr1[e.id] && (mapOfArr1[e.id].y = false);
});

使用map 函数咯


const arr1 = [{id:1,name:"a",y:true}
               ,{id:2,name:"b",y:true}
               ,{id:3,name:"c",y:true}
               ,{id:4,name:"d",y:true}
               ,{id:5,name:"e",y:true}
            ];
const arr2 = [{id:1,name:"a",y:true},{id:2,name:"b",y:true}];

let tmap = {}

arr2.forEach(ele=>tmap[ele.id]=true)

let arr1X = arr1.map(ele=> Object.assign({},ele,!tmap[ele.id]?{}:{y:false}) )

console.log(arr1X)

改成这样会比较快


arr2.forEach(ele=>tmap[ele.id]=true)

arr1.forEach(ele=> {
    if(!tmap[ele.id]){
        ele.y = false
    }
})

http://jsperf.com/resolve2array1010000004329153/5


var arr1 = [{id: 1, name: "a", y: true}, {id: 2, name: "b", y: true}, {id: 3, name: "c", y: true}, {id: 4, name: "d", y: true}, {id: 5, name: "e", y: true}];
var arr2 = [{id: 1, name: "a", y: true}, {id: 2, name: "b", y: true}];
var val = JSON.stringify(arr2);
arr1.forEach(function (item) {
     if (new RegExp('"id":' + item.id, 'g').test(val)) {
          item.y = false;
     }
});

利用Array的sort方法及concat方法引用复制的特点来实现查找

concat方法引用复制

Object references (and not the actual object): concat copies object references into the new array. Both the original and new array refer to the same object. That is, if a referenced object is modified, the changes are visible to both the new and original arrays.
Strings and numbers (not String and Number objects): concat copies the values of strings and numbers into the new array.

sort方法
如果2者相同,那么不交换彼此的位置,也就是说如果arr1中的某项a和arr2中的某项b相同,那么排序结束后,
a会一一直保持在b元素的前面

var arr1 = [{id:1,name:"a",y:true},{id:2,name:"b",y:true},{id:3,name:"c",y:true},{id:5,name:"d",y:true},{id:7,name:"e",y:true}];
var arr2 = [{id:1,name:"a",y:true},{id:2,name:"b",y:true},{id:7,name:"b",y:true},{id:5,name:"b",y:true}];

arr1.concat(arr2).sort(function(a,b){
    if(a.id== b.id){
        a.y=false;
    }
    return a.id-b.id;

});
console.log(arr1);

没有嵌套 :)

var arr1 = [{id:1,name:"a",y:true},{id:2,name:"b",y:true},{id:3,name:"c",y:true},{id:4,name:"d",y:true},{id:5,name:"e",y:true}];
var arr2 = [{id:1,name:"a",y:true},{id:2,name:"b",y:true},{id:4,name:"b",y:true}];

var x = [];

arr1.forEach(v => x[v.id] = v);

arr2.forEach(v => x[v.id] && (x[v.id].y = false));

x = null;

console.log(arr1); // 结果
【热门文章】
【热门文章】