I have two arrays like
var members = [{docId: \"1234\", userId: 222}, {docId: \"1235\", userId: 333}];
var memberInfo = [{id: 222, name: \"test1\"}, {id: 333
A solution using underscore:
var finalArray = _.map(members, function(member){
return _.extend(member, _.omit(_.findWhere(memberInfo, {id: member.userId}), 'id'));
});
Do a nested map and update the top level element with the additional field date
where fields in the arrays match.
member.map(mem => {
return memberInfo.map(info => {
if (info.id === mem.userId) {
mem.date = info.date;
return mem;
}
}
}
On ES6 you can use .find and Object.assign() in vanilla javascript, no need of extra libraries.
let finalArray = [];
memberInfo.forEach(member => {
finalArray.push( Object.assign( {}, member,
{ docId: members.find(m => m.userId === member.id).docId }
))
});
var members = [{
docId: "1234",
userId: 222
}, {
docId: "1235",
userId: 333
}];
var memberInfo = [{
id: 222,
name: "test1"
}, {
id: 333,
name: "test2"
}];
var finalArray = [];
_.each(memberInfo, function (item) {
finalArray.push(_.each(_.where(members, {
userId: item.id
}),
function (element) {
element.name = item.name
}));
});
console.log(finalArray);
Fiddle example
You can achieve using foreach function
and creating the third array and displaying it.
$scope.members = [{docId: "1234", userId: 222}, {docId: "1235", userId: 333}];
$scope.memberInfo = [{id: 222, name: "test1"}, {id: 333, name: "test2"}];
$scope.finalArray = [];
angular.forEach($scope.members, function(member) {
angular.forEach($scope.memberInfo, function(memberInfo) {
if(member.userId ==memberInfo.id) {
var test = {
docId : member.docId,
userId: member.userId,
name: memberInfo.name
}
$scope.finalArray.push(test);
}
});
});
Here is the working plunker:
http://embed.plnkr.co/QRB5v2cI6SZOdZgdqDVR/preview
Hope it helps!
function computeMembers(members, memberInfo) {
return members.map(function(member) {
member.name = memberInfo[getMemberById(member.userId, memberInfo)].name
return member
})
function getMemberById(id, elements) {
var index = elements.filter(function(element) {
return element.id === id
})[0]
return elements.indexOf(index)
}
}
console.log(computeMembers(members, memberInfo))