0

I am new at Javascript, and I am having problems with a list of dictionaries. I have an object such as this one:

0:{Year: "2007", expenditure: "314,448.7", category: "Exports"}
1:{Year: "2008", expenditure: "320,805.2", category: "Exports"}
2:{Year: "2007", expenditure: "314,448.7", category: "Imports"}
3:{Year: "2008", expenditure: "320,805.2", category: "Imports"}

and I would like to turn it into a new one with the values Exports and Imports as two different columns, with its correspondent expenditure below. Something like this:

0:{Year: "2007", Exports: "314,448.7"}
1:{Year: "2008", Exports: "320,805.2"}
2:{Year: "2007", Imports: "314,448.7"}
3:{Year: "2008", Imports: "320,805.2"}

Does anyone know how to do this? Thank you in advance.

Michael Ro
  • 19
  • 3
  • FYI In JavaScript these are not dictionaries, they're Objects – zfrisch Apr 13 '18 at 19:58
  • @barmar today you are closing everything. The dupe seems to be just slightly related. – Jonas Wilms Apr 13 '18 at 20:00
  • @JonasW. Unless he doesn't know how to loop over an array, what other problem could he have than creating a new object with a dynamic property name? – Barmar Apr 13 '18 at 20:02
  • Sorry, I made a mistake in my question. What I would like to get is something like this: 0:{Year: "2007", Exports: "314,448.7", Imports: "314,448.7"} 1:{Year: "2008", Exports: "320,805.2", Imports: "320,805.2"} – Michael Ro Apr 14 '18 at 09:22

2 Answers2

0

This would be a good job for reduce:

let arry = [{
    Year: "2007",
    expenditure: "314,448.7",
    category: "Exports"
  },
  {
    Year: "2008",
    expenditure: "320,805.2",
    category: "Exports"
  },
  {
    Year: "2007",
    expenditure: "314,448.7",
    category: "Imports"
  },
  {
    Year: "2008",
    expenditure: "320,805.2",
    category: "Imports"
  }
]

let result = arry.reduce((r, v) => r.concat([{
  Year: v.Year,
  [v.category]: v.expenditure
}]), [])

console.log(result)
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
0
    const output = input.map(({Year, expenditure, category}) => ({Year, [category]: expenditure }));

Just destructure every object and build up a new one. You can also include all other propertues in the new object using rest/spread:

 const output = input.map(({expenditure, category, ...rest}) => ({[category]: expenditure, ...rest }));
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • 1
    @GetOffMyLawn map returns a new array, and the OP asked to transform the current array into the two key one. – zfrisch Apr 13 '18 at 19:59