'Merge two array of objects using lodash
I have two arrays of objects called movies and movieDetails:
const movies = [{
movieID: 0,
movieDetailsID: 9,
movieName: "Dragonball Z",
cost: 10
},
{
movieID: 1,
movieDetailsID: 10,
movieName: "Spider Man",
cost: 15
},
{
movieID: 2,
movieDetailsID: 11,
movieName: "John Wick",
cost: 20
}
];
const movieDetails = [{
movieDetailsID: 10,
actor: "John Doe",
fee: 100
},
{
movieDetailsID: 10,
actor: "Harry Styles",
fee: 120
},
{
movieDetailsID: 11,
actor: "John Bane",
fee: 200
}
];
- I would like to some how merge these two array of objects and add details only if there is a matching movieDetailsID. I was thinking of using low dash for this?
- I would like to choose each objects (column names) I want to see from movies and movies details in my output i.e, for movies: movie name and cost. and movie details: actor and cost.
Expected Output:
{
movieID: 0,
movieDetailsID: 9,
movieName: "Dragonball Z",
cost: 10
}, {
movieID: 1,
movieDetailsID: 10,
movieName: "Spider Man",
cost: 15,
details: [{
movieDetailsID: 10,
actor: "John Doe",
fee: 100
},
{
movieDetailsID: 10,
actor: "Harry Styles",
fee: 120
}
]
}, {
movieID: 2,
movieDetailsID: 11,
movieName: "John Wick",
cost: 20,
details: [{
movieDetailsID: 11,
actor: "John Bane",
fee: 200
}]
}
What I have tried . However this seems to merge it in and doesnt create a seperate ovject details to add in those matching movie details ids.
var mergedList = _.map(movies, function(item){
return _.extend(item, _.findWhere(movieDetailsID, { movieDetailsID: item.movieDetailsID }));
});
Solution 1:[1]
There you are, lodash solution, extremely simple
import groupBy from "lodash/groupBy";
import reduce from "lodash/reduce";
const result = reduce(movies, ([movieDetailsIndex, res], movie) => [
movieDetailsIndex,
[...res, {...movie, ...(movieDetailsIndex[movie.movieDetailsID] ?
{details: movieDetailsIndex[movie.movieDetailsID]} : {}
)}]
], [groupBy(movieDetails, "movieDetailsID"), []])[1];
Solution 2:[2]
Try this:
body {
background-image: url("https://media.istockphoto.com/photos/picking-the-right-paint-paint-sample-color-swatch-picture-id92241441?b=1&k=20&m=92241441&s=170667a&w=0&h=OudUCphkJO9Gx9AdVpYIIypg48ELx72Zd46W818fTa8=");
background-size: cover;
background-repeat: no-repeat;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Igor Loskutov |
| Solution 2 | Nico Halpe |
