Merge Two Arrays Matching An Id
I have two arrays like var members = [{docId: '1234', userId: 222}, {docId: '1235', userId: 333}]; var memberInfo = [{id: 222, name: 'test1'}, {id: 333, name: 'test2'}]; I need to
Solution 1:
A solution using underscore:
var finalArray = _.map(members, function(member){
return _.extend(member, _.omit(_.findWhere(memberInfo, {id: member.userId}), 'id'));
});
- _.map across the members
- find the matching member info using _.findWhere
- _.omit the id key from the matching member info
- _.extend the member with the member info
Solution 2:
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!
Solution 3:
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))
Solution 4:
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);
Solution 5:
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 }
))
});
Post a Comment for "Merge Two Arrays Matching An Id"