I'm new to JavaScript. I want to arrange the following array
{
"movies": [
{ "id": "1", "competition":1, "time":1670854636, "title": "Star Wars", "releaseYear": "1977" },
{ "id": "2", "competition":1, "time":1670854636, "title": "Back to the Future", "releaseYear": "1985" },
{ "id": "3", "competition":2, "time":1670937436, "title": "The Matrix", "releaseYear": "1999" },
{ "id": "4", "competition":1, "time":1670937436, "title": "Inception", "releaseYear": "2010" },
{ "id": "5", "competition":2, "time":1670937436, "title": "Interstellar", "releaseYear": "2014" }
]
}
into this one, where the first key is time and the nested is competition
{
"movies": [
{"time": 1670854636, "competitions": [
"competition":1, "data": [
{"title": "Star Wars", "releaseYear": "1977"},
{"title": "Back to the Future", "releaseYear": "1985"}
]
]},
{"time": 1670937436, "competitions": [
"competition":1, "data": [
{"title": "The Matrix", "releaseYear": "1999"}
],
"competition":2, "data": [
{"title": "Inception", "releaseYear": "2010"},
{"title": "Interstellar", "releaseYear": "2014"}
]
]}
]
}
I tried this, and it works, but I can't reproduce the same logic for nested competition array
var result = json.movies.reduce((actual, match) => {
const { time, ...restOfMovie } = movie;
const group = actual.find((item) => movie.time === time);
if (!group) {
actual.push({
time: time
});
}
return actual;
}, []);
How should I complete the code?