[英]Javascript compare 2 object arrays with where conditions
我正在尝试比较两个对象数组,例如
list1 = [{id:1,name:'amy'},{id:3,name:'zoe'}];
list2 = [{id:1,name:'sally'},{id:3,name:'zoe'}];
select *
from list1 a, list2 b
where a.id = b.id
and a.name = b.name
Result: id:3, name:'zoe'
我怎样才能用 Javascript 写这个?
您需要遍历两个数组并匹配值。
list1 = [{id:1,name:'amy'},{id:3,name:'zoe'}]; list2 = [{id:1,name:'sally'},{id:3,name:'zoe'}]; var r = []; list1.forEach(function(a){ return list2.forEach(function(b){ if(a.id === b.id && a.name === b.name) r.push(b) }) }); console.log(r)
你可以试试这个:
var list1 = [{id:1,name:'amy'},{id:3,name:'zoe'}]; var list2 = [{id:1,name:'sally'},{id:3,name:'zoe'}]; var r = list1.filter(x => list2.some(y => x.name == y.name && x.id == y.id))[0]; console.log(r);
您可以在哈希表中收集list1
所有id
和name
,并稍后检查是否存在。
var list1 = [{ id: 1, name: 'amy' }, { id: 3, name: 'zoe' }], list2 = [{ id: 1, name: 'sally' }, { id: 3, name: 'zoe' }], list1hash = Object.create(null), result; list1.forEach(function (a) { list1hash[[a.id, a.name].join('|')] = a; }); result = list2.filter(function (a) { return list1hash[[a.id, a.name].join('|')]; }); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
如何按 id 对两个数组进行排序,然后同时对它们进行迭代?
它应该导致2 * O(n*logn) + n
复杂性,这比其他人建议的n^2
好得多。
另一个(es6):
const list1 = [{id:1,name:'amy'},{id:3,name:'zoe'}]; const list2 = [{id:1,name:'sally'},{id:3,name:'zoe'}]; const result = list1.reduce((acc, a) => acc.concat(list2.filter(b => a.id === b.id && a.name === b.name)),[]); console.log('result :', result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.