Merging/Joining 2 array objects on attribute in lodash

619 views Asked by At

Is it possible to merge two array object based on an attribute present in both arrays.

I would like to achieve this via lodash lib.

eg Consider a list of catogories with id as PK and a list of movies with catagoryId as a FK

Array of movie category:

[{
    id: "cartoon",
    catagoryName:"Cartoon", 
},{
    id: "drama",
    catagoryName:"Drama",   
},{
    id: "action",
    catagoryName:"Action",  
}]

Array of movies.

[{
    categoryId:"action",
    movieName:"Spy",
    year: 2015
},{
    categoryId:"drama",
    movieName:"San Andreas",
    year: 2015
},{
    categoryId:"cartoon",
    movieName:"Rio",
    year: 2013
},{
    categoryId:"action",
    movieName:"Jurassic World",
    year: 2015
}]

The output that that i am looking for via underscore or lodash.

[{
    id: "cartoon",
    catagoryName:"Cartoon",
    movies:[{
        categoryId:"cartoon",
        movieName:"Rio",
        year: 2013
    }]
},{
    id: "drama",
    catagoryName:"Drama",   
    movies:[{
        categoryId:"drama",
        movieName:"San Andreas",
        year: 2015
    }]
},{
    id: "action",
    catagoryName:"Action",
    movies:[{
        categoryId:"action",
        movieName:"Jurassic World",
        year: 2015
    },{
        categoryId:"action",
        movieName:"Spy",
        year: 2015
    }]  
}]

I know i can do this with for loop but wanted to know if there is a better cleaner way.

Any suggestions can help. This is node js applications.

1

There are 1 answers

4
Aaron Dufour On BEST ANSWER

I used groupBy to group the movies by their category, and then maped the categories by extending them with the proper list of movies.

groupedMovies = _.groupBy(movies, 'categoryId');

_.map(categories, function(cat) {
  return _.extend({movies: groupedMovies[cat.id] || []}, cat);
})

var categories =
[{
    id: "cartoon",
    catagoryName:"Cartoon",
},{
    id: "drama",
    catagoryName:"Drama",
},{
    id: "action",
    catagoryName:"Action",
}];

var movies =
[{
    categoryId:"action",
    movieName:"Spy",
    year: 2015
},{
    categoryId:"drama",
    movieName:"San Andreas",
    year: 2015
},{
    categoryId:"cartoon",
    movieName:"Rio",
    year: 2013
},{
    categoryId:"action",
    movieName:"Jurassic World",
    year: 2015
}];

groupedMovies = _.groupBy(movies, 'categoryId');
_.map(categories, function(cat) {
  return _.extend({movies: groupedMovies[cat.id] || []}, cat);
})

document.write("<pre>" + JSON.stringify(groupedMovies, null, 2) + "</pre>");
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/3.9.3/lodash.min.js"></script>

Note: This leaves both categories and movies unchanged.