我有两个对象数组来合并它们。第一个是snapshotChanges检索(参与者)的结果,第二个是valueChanges检索(usersRoom)的结果。
//First one (participants)
participants = [
{id: 123, message: 'OK'},
{id: 456, message: 'Hey'}
];
//Second one (usersRoom)
for(var i=0; i < this.participants.length; i++){
this.room = this.db.object('users/' + this.participants[i].id).valueChanges();
this.room.subscribe(
res => {
this.usersRoom.push(res);
});
}
但是当我尝试使用下面的代码合并它们时,将返回一个空数组:
this.final = this.usersRoom.reduce((arr, e) => {
arr.push(Object.assign({}, e, this.participants.find(a => a.id === e.id)))
return arr;
}, [])
我检查了是否创建了假对象,而不是获取valueChanges,只是为了验证运行上面的合并并完美运行的代码。
在结果中运行console.log时,我注意到它们在控制台上的显示方式不同(请参见第一行):
//participants
(2) [{…}, {…}]
0: {id: "123", message: "OK"}
1: {id: "456", message: "Hey"}
//usersRoom
[]
0: {name: "John", age: "28", id: "123"}
1: {name: "Mary", age: "32", id: "456"}
在我看来,两者的格式不同,因此最终没有被合并。 那么我该怎么做才能合并它们?
答案 0 :(得分:0)
如果我理解正确,那么您正在尝试获取该信息
merge(){
let ids = [];
let merge_obj = [];
let participants = [
{id: 123, message: 'OK'},
{id: 456, message: 'Hey'}
];
let usersRoom = [
{name: "John", age: "28", id: "123"},
{name: "Mary", age: "32", id: "456"}
];
participants.map( (obj) => {
let index = ids.indexOf(obj.id);
if( !( index > -1 ) )
{
ids.push(obj.id.toString());
}
});
usersRoom.map( (obj) => {
let index = ids.indexOf(obj.id);
if( !(index > -1 ) )
{
merge_obj.push(obj);
}
else
{
let keys : Array<string> = Object.keys( obj );
let objMerge = participants.filter( o => {
if( o.id.toString() == obj.id )
{
let keysMerge : Array<string> = Object.keys( o );
keysMerge.forEach( value => {
if ( keys.indexOf(value) == -1 ) {
obj[value]=o[value];
}
});
}
return obj;
})
merge_obj.push(obj);
}
});
console.log(merge_obj);
}
merge_obj
0: {name: "John", age: "28", id: "123", message: "OK"}
1: {name: "Mary", age: "32", id: "456", message: "Hey"}