javascript如何从两个对象数组中找到?

时间:2017-04-14 09:06:38

标签: javascript arrays

我有两个数组对象

 var data=[{m:1},{m:2},{m:3},{m:4},{m:5},{m:6},{m:7},{m:8},{m:9},{m:10},{m:11},{m:12}];
 var file=[{m:1},{m:3}];

我希望得到像[true,false,false,true,false,false,false,false,false,false,false,false]

这样的数组

注意:在这个ayyar中,如果它与数据数组对象中的文件数组对象匹配,它将返回true。

我尝试indexOf,但我无法为我的结果工作。

5 个答案:

答案 0 :(得分:5)

使用Array.prototype.map()Array.prototype.some()



 let data = [{m:1},{m:2},{m:3},{m:4},{m:5},{m:6},{m:7},{m:8},{m:9},{m:10},{m:11},{m:12}];
 let file = [{m:1},{m:3}];
 
 let result = data.map(d => file.some(f => f.m === d.m));
 
 console.log(result);




答案 1 :(得分:4)

您可以使用哈希表并映射出现。

var data = [{ m: 1 }, { m: 2 }, { m: 3 }, { m: 4 }, { m: 5 }, { m: 6 }, { m: 7 }, { m: 8 }, { m: 9 }, { m: 10 }, { m: 11 }, { m: 12 }],
    file = [{ m: 1 }, { m: 3 }],
    hash = Object.create(null),
    result;
    
file.forEach(function (a) {
    hash[a.m] = true;
});

result = data.map(function (a) {
    return hash[a.m] || false;
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

ES6与Set

var data = [{ m: 1 }, { m: 2 }, { m: 3 }, { m: 4 }, { m: 5 }, { m: 6 }, { m: 7 }, { m: 8 }, { m: 9 }, { m: 10 }, { m: 11 }, { m: 12 }],
    file = [{ m: 1 }, { m: 3 }],
    mySet = new Set(file.map(a => a.m)),
    result = data.map(a => mySet.has(a.m));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:1)

试试这个Demo

var data=[{m:1},{m:2},{m:3},{m:4},{m:5},{m:6},{m:7},{m:8},{m:9},{m:10},{m:11},{m:12}];
 var file=[{m:1},{m:3}];
 var re = [];
 for(var i=0;i<data.length;i++){
 	let r = file.find(function findObj(o) { 
    return o.m === data[i].m;
	})
if(r){
  	re.push(true)
  }else{
  re.push(false)
  }
 }
 console.log(re)

答案 3 :(得分:0)

有趣的是ES6变得多么微不足道。

在这里,file.map(val => val.m)会给我一系列数字。 [1, 3]我用来查找它是否包含当前对象的m道具。

&#13;
&#13;
 var data=[{m:1},{m:2},{m:3},{m:4},{m:5},{m:6},{m:7},{m:8},{m:9},{m:10},{m:11},{m:12}];
 var file=[{m:1},{m:3}];
 var selection = file.map(val => val.m)
 
 var arr = data.map(obj => selection.includes(obj.m))
 
 console.log(arr)
&#13;
&#13;
&#13;

答案 4 :(得分:0)

var data = [{m:1},{m:2},{m:3},{m:4},{m:5},{m:6},{m:7},{m:8},{m:9},{m:10},{m:11},{m:12}];
var file = [{m:1},{m:3}];

var result = [];

function remove_duplicates(data, file) {
    for (var i = 0, len = data.length; i < len; i++) { 
        for (var j = 0, len2 = file.length; j < len2; j++) { 
            if (data[i].m === file[j].m) {
                result.push("true")
            }else{
            result.push("false")
            }
        }
    }
console.log(result)
}

remove_duplicates(data,file);