在lodash中合并/连接属性上的2个数组对象

时间:2015-06-12 16:52:52

标签: javascript node.js lodash

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

我想通过lodash lib实现这一目标。

例如,考虑一个id为PK的catogories列表和一个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循环来做这件事,但想知道是否有更好的清洁方式。

任何建议都有帮助。这是节点js应用程序。

1 个答案:

答案 0 :(得分:3)

我使用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>

注意:这会使categoriesmovies保持不变。