我正在尝试将一个对象的值添加到另一个对象(如果两者具有相同的值)。
对象基本上是这样的:
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.username
添加到 comments.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
对象已经排序,这也是它不能被打乱的原因。
这是我当前的代码,但它根本不起作用:
comments.forEach(function(i, index) {
users.forEach(function(e) {
if(e._id == i.author) {
comments[index].username = e.username;
}
});
});
最佳答案
Array.forEach
的回调将对象 作为第一个参数,而不是索引。所以改成这样:
comments.forEach(function(comment) {
users.forEach(function(user) {
if (user._id === comment.author) {
comment.username = user.username;
}
});
});
还想指出,像这样的嵌套循环对于大量数据集来说是众所周知的坏主意;它的复杂度为 O(N*M)
。此外,一旦找到匹配项,循环就会继续。我建议您首先创建一个用户查找,这样每个查找都是一个 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;
}
});
关于javascript - 合并具有相同值的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27714654/