javascript - 如何搜索两个数组并查找是否匹配?

标签 javascript underscore.js

我有一个数组:

[{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/

相关文章:

javascript - 关闭编译器警告 `dangerous use of the global this object`?

javascript - IE6 中的 event.returnValue

angularjs - 我应该使用 Angular.copy() 还是 _.clone()?

javascript - 在 JS 中扩展和合并两个数组(包含对象)

javascript - 为什么 `ng-checked` 不能与 `ng-change` 一起使用?

javascript - HTML5/jQuery 动画上的计时器/间隔

javascript - Jquery 首先选中复选框

javascript - 在 Underscore JS 中编写我的 _.reject 版本

javascript - 检查集合中是否有任何脏的 Backbone 模型数据

javascript - 为什么强调原型(prototype)链之外的别名方法?