在lodash属性上合并/连接两个数组对象

是否有可能根据两个数组中存在的属性合并两个数组对象。

我想通过lodash lib来实现这个function。

例如,考虑id为PK的列表,以及catagoryId为FK的电影列表

电影类别数组:

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

一些电影。

 [{ 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 }] 

我正在通过下划线或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 }] }] 

我知道我可以做for循环,但想知道是否有更好的更清洁的方式。

任何build议可以帮助。 这是节点的js应用程序。

       

网上收集的解决方案 "在lodash属性上合并/连接两个数组对象"

我用groupBy按类别对电影进行分组,然后通过扩展电影列表来map分类。

 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>