合并具有相同值的对象

我想从一个对象添加一个值到另一个,如果两者具有相同的值。

这是对象基本上是这样的:

var comments = [ { author: '4jdf7s', message: 'Comment text here', posted: '2014-12-29 14:30' }, { author: '87sd3w', message: 'Comment text here', posted: '2014-12-30 12:00' } ]; var users = [ { _id: '87sd3w', username: 'MyUsername' }, { _id: '4jdf7s', username: 'OtherUsername' } ]; 

作为author_id是相同的,我想添加users.usernamecomments.username像这样:

 var comments = [ { author: '4jdf7s', username: 'OtherUsername', message: 'Comment text here', posted: '2014-12-29 14:30' }, { author: '87sd3w', username: 'MyUsername', message: 'Comment text here', posted: '2014-12-30 12:00' } ]; 

comments对象已被sorting,这就是为什么它不能被炒。

这是我目前的代码,但它根本不起作用:

 comments.forEach(function(i, index) { users.forEach(function(e) { if(e._id == i.author) { comments[index].username = e.username; } }); }); 

Array.forEach的callbackArray.forEach对象作为第一个参数,而不是索引。 所以改为这样:

 comments.forEach(function(comment) { users.forEach(function(user) { if (user._id === comment.author) { comment.username = user.username; } }); }); 

还想指出,像这样的嵌套循环对于大量的数据是一个糟糕的主意, 它具有O(N*M)复杂性。 另外,一旦你find一个匹配,循环继续。 我build议你先创build一个用户查找,以便每个查找是O(1) ,将整个代码转换为O(N)

 var usersById = {}; users.forEach(function(user) { usersById[user._id] = user; }); comments.forEach(function(comment) { var user = usersById[comment.author]; if (user) { comment.username = user.username; } }); 

您可以预防作者以避免内部循环。

 var cache = users.reduce(function(acc, user){ acc[user._id] = user.name; return acc;}, {} ); comments.forEach(function(comment){ comment.username = cache[comment.author]; });