Melina Melina - 1 month ago 6
Javascript Question

Can I use _lodash to update an array with data from another?

I have an array called grid.data that has an assignedTo field which is a Id value (25 and 26) in this example. I also have another array called userProfiles that has an id and a name field.

var grid.data = [
{"cityId":9,"assignedTo":"25"},
{"cityId":63,"assignedTo":"26"}];

var userProfiles = [
{"id":"25","name":"john"},
{"id":"26","name":"jacky"}];


I have the following function:

var getUser = function (userId) {
if (userId && userProfiles)
for (var i = 0; i < userProfiles.length; i++)
if (userProfiles[i].id === userId)
return userProfiles[i].name;
return '';
}


Is it possible for me to use _lodash to call the getUser function with
the assignedTo values and replace the assignedTo with the user name
that's returned? Alternatively (if it's a better way), could I combine the grid.data and the $scope.option.userProfiles with _lodash and avoid having to call getUser?

This is the output I need:

var grid.newData = [
{"cityId":9,"assignedTo":"john"},
{"cityId":63,"assignedTo":"jacky"}];

Answer

you could combine an _.map and a _.where....

grid.newData = _.map(grid.data, function(item) {
    var profile = _.where(userProfiles, {id : item.assignedTo})[0];
    return {
        cityId : item.cityId,
        assignedTo : profile.name
    }
});
Comments