Home > OS >  JavaScript: Convert array of objects into array of object of array of object
JavaScript: Convert array of objects into array of object of array of object

Time:05-12

JavaScript: Convert array of objects into array of object of array of objects

Convert: Input

[{date: 2021, name: 'New York', price: 452}, {date: 2020, name: 'New York', price: 452}, {date: 2021, name: 'Oregon', price: 452} , .... ]

The output required is:

        {
           name: "New York",
           values: [
             {date: "2000", price: "50"},
             {date: "2001", price: "10"},
             {date: "2002", price: "5"},
             {date: "2003", price: "71"},
             {date: "2004", price: "20"},
             {date: "2005", price: "9"},
             {date: "2006", price: "220"},
             {date: "2007", price: "235"},
             {date: "2008", price: "61"},
             {date: "2009", price: "10"}
           ]
         },
         
         {
           name: "Oregon",
           values: [
             {date: "2000", price: "20"},
             {date: "2001", price: "10"},
             {date: "2002", price: "5"},
             {date: "2003", price: "71"},
             {date: "2004", price: "20"},
             {date: "2005", price: "9"},
             {date: "2006", price: "220"},
             {date: "2007", price: "235"},
             {date: "2008", price: "61"},
             {date: "2009", price: "10"}
           ]
         }
       ];

CodePudding user response:

You can do something like this

const data = [{date: 2021,name: 'New York',price: 452}, {date: 2020,name: 'New York',price: 452}, {date: 2021,name: 'Oregon',price: 452}]

const result = Object.values(data.reduce((res, {name,...rest}) => {
  return {
    ...res,
    [name]: {
      name,
      values: [...(res[name] || {values: []}).values, rest]
    }
  }
}, []))

console.log(result)

  • Related