Usando la función de reduce , me gustaría obtener directores y sus títulos en un objeto. Accidentalmente lo inicialicé como una matriz vacía en lugar de un objeto. Pero descubrí que llamar a Object.entries en esta matriz vacía estaba devolviendo algo.
Y me gustaría entender por qué esto devuelve algo. ¿Se trata de referencias?
Código:
const films = [ { director: "Hayao Miyazaki", title: "title1" }, { director: "Hayao Miyazaki", title: "title2" }, { director: "Gerard", title: "title1" }, { director: "Gerard", title: "title1" }, { director: "Anne", title: "title1" }, ]; // we want an object of directors and their titles, using reduce const directorsFilms = films.reduce((a, { director, title }) => { if (!a[director]) a[director] = []; a[director].push(title); return a; }, []); // my mistake, should have been an empty object "{}" // prints something in PythonTutor but not in Codepen. // referenced to an empty array console.log(directorsFilms); // but when you call Object.entries on this empty array, there are results // I call Object.fromEntries to get the object I was supposed to have calling reduce, not important const tmp = Object.fromEntries(Object.entries(directorsFilms)); console.log(tmp);No entiendo cómo es esto posible... Agradecería alguna idea. ¡Gracias por adelantado! :)