Home > Blockchain >  I want to convert This array to this object
I want to convert This array to this object

Time:07-03

const movies = [
  { name: "Escape from Pretoria", year: 2020 },
  { name: "Good Will Hunting", year: 1997 },
  { name: "The Matrix", year: 1999 },
  { name: "Tarzan", year: 1999 },
  { name: "Titanic", year: 1997 },
  { name: "The Imitation Game", year: 2014 },
];

to object like this

const x = {
  1997: ["Good will Hunting", "Titanic"],
  1999: ["The Matrix", "Tarazan"],
  2014: ["The Imitation Game"],
  2020: ["Escape from Pretoria"],
};

Using reduce() or another way .. thank you!

CodePudding user response:

    const movies = [
  { name: "Escape from Pretoria", year: 2020 },
  { name: "Good Will Hunting", year: 1997 },
  { name: "The Matrix", year: 1999 },
  { name: "Tarzan", year: 1999 },
  { name: "Titanic", year: 1997 },
  { name: "The Imitation Game", year: 2014 },
];

let obj={};

movies.forEach(({year, name})=>{
  if(obj[year]){
    obj[year].push(name)
  } else {
    obj[year] = [name]
  }

})

console.log(obj);

CodePudding user response:

Here's a solution using reduce

const movies = [
  { name: "Escape from Pretoria", year: 2020 },
  { name: "Good Will Hunting", year: 1997 },
  { name: "The Matrix", year: 1999 },
  { name: "Tarzan", year: 1999 },
  { name: "Titanic", year: 1997 },
  { name: "The Imitation Game", year: 2014 },
];

const result = movies.reduce((acc, curr) => {
  if (acc[curr.year]) acc[curr.year].push(curr.name)
  else acc[curr.year] = [curr.name]
  return acc
}, {})

console.log(result)

  • Related