0

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?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Adriano Bellavita
  • 143
  • 1
  • 3
  • 12
  • From the above description and especially from ... _"I tried this, and it works, but I can't reproduce the same logic for nested competition array"_ ... it does nor clarify what the result of the OP's try (the provided reduce based code) actually is and/or if the presented code fails in the creation of the OP's expected result. – Peter Seliger Dec 14 '22 at 10:05

0 Answers0