我有两个用户对象数组,其中包含_id和lastSeen。
allUsersSeen = [
{_id: '12csdf', lastSeen: 212512},
{_id: '232csdf', lastSeen: 34345},
{_id: '1253csdf', lastSeen: 6346453},
{_id: '772csfddf', lastSeen: 2345345}
]
currentUsersSeen = [
{_id: '12csdf', lastSeen: Date.now()},
{_id: '1253csdf', lastSeen: Date.now()},
{_id: '1fsdf', lastSeen: Date.now()}
]
我想比较这两个数组,如果allUsersSeen _id与currentUsersSeen匹配,我想将lastSeen更新为Date.now()。所有其他_id将使其lastSeen保持原样。
来自currentUsersSeen的任何剩余_id应该使用lastSeen of Date.now()
推送到allUsersSeen上allUsersSeen的最终数组应如下所示:
allUsersSeen = [
{_id: '12csdf', lastSeen: Date.now()},
{_id: '232csdf', lastSeen: 34345},
{_id: '1253csdf', lastSeen: Date.now()},
{_id: '772csfddf', lastSeen: 2345345},
{_id: '1fsdf', lastSeen: Date.now()}
]
显然,Date.now()将是当前的日期/时间。 我该怎么做呢? 我尝试过使用嵌套的for循环,并尝试使用forEach()和map()。
非常感谢任何帮助。 谢谢。
答案 0 :(得分:0)
你可能想要那样的东西
allUsersSeen = [
{_id: '12csdf', lastSeen: 212512},
{_id: '232csdf', lastSeen: 34345},
{_id: '1253csdf', lastSeen: 6346453},
{_id: '772csfddf', lastSeen: 2345345}
]
currentUsersSeen = [
{_id: '12csdf', lastSeen: Date.now()},
{_id: '1253csdf', lastSeen: Date.now()},
{_id: '1fsdf', lastSeen: Date.now()}
]
let newArr = allUsersSeen.map(user => currentUsersSeen.find(curr_user => curr_user._id === user._id) || user);
答案 1 :(得分:0)
如果您了解自己要做的事情,可以先从allUsersSeen(如果存在)中删除该元素,然后再从currentUser中再次添加该元素,从而实现这一目标。
allUsersSeen = [
{_id: '12csdf', lastSeen: 212512},
{_id: '232csdf', lastSeen: 34345},
{_id: '1253csdf', lastSeen: 6346453},
{_id: '772csfddf', lastSeen: 2345345}
]
currentUsersSeen = [
{_id: '12csdf', lastSeen: Date.now()},
{_id: '1253csdf', lastSeen: Date.now()},
{_id: '1fsdf', lastSeen: Date.now()}
]
currentUsersSeen.forEach(user => {
allUsersSeen = allUsersSeen.filter( obj => obj._id != user.id )
allUsersSeen.push(user)
})
答案 2 :(得分:0)
试试这个,
allUsersSeen = [
{_id: '12csdf', lastSeen: 212512},
{_id: '232csdf', lastSeen: 34345},
{_id: '1253csdf', lastSeen: 6346453},
{_id: '772csfddf', lastSeen: 2345345}
];
currentUsersSeen = [
{_id: '12csdf', lastSeen: Date.now()},
{_id: '1253csdf', lastSeen: Date.now()},
{_id: '1fsdf', lastSeen: Date.now()}
];
function merge(a, b, prop){
var reduced = a.filter( a_item => ! b.find ( b_item => a_item[prop] === b_item[prop]) )
return reduced.concat(b);
}
console.log( merge(allUsersSeen, currentUsersSeen, "_id") );
答案 3 :(得分:0)
您可以array#concat
两个数组,然后使用array#reduce
更新lastSeen
。
var allUsersSeen = [{_id: '12csdf', lastSeen: 212512},{_id: '232csdf', lastSeen: 34345},{_id: '1253csdf', lastSeen: 6346453},{_id: '772csfddf', lastSeen: 2345345}],
currentUsersSeen = [{_id: '12csdf', lastSeen: Date.now()},{_id: '1253csdf', lastSeen: Date.now()},{_id: '1fsdf', lastSeen: Date.now()}],
result = Object.values( allUsersSeen.concat(currentUsersSeen).reduce((r, {_id, lastSeen}) => {
r[_id] = r[_id] ? {...r[_id], lastSeen} : {_id, lastSeen};
return r;
},{}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }