我有一个数组:
[{name:'blah',id:1},{name:'blah2',id:3}]
我有另一个数组:
[{type:'blah',uid:3435},{type:'blah2',uid:3}]
我想结束:
[{newname:'blah2',uidid:3}]
您可以看到我想根据 id=uid 的映射来匹配两者。真的很难找到一种方法来在js中做到这一点。我安装了下划线
。
最佳答案
您可以使用第一个数组构建一个哈希表,并在第二个数组的迭代中使用它。
var array1 = [{ name: 'blah', id: 1 }, { name: 'blah2', id: 3 }],
array2 = [{ type: 'blah', uid: 3435 }, { type: 'blah2', uid: 3 }],
hash = Object.create(null),
match = [];
array1.forEach(function (a) {
hash[a.id] = a;
});
array2.forEach(function (a) {
hash[a.uid] && match.push({ newname: a.type, uidid: a.uid });
});
console.log(match);
关于javascript - 如何搜索两个数组并查找是否匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37949358/