0

I'm converting excel to Json, after the conversion is done I'm getting the below JSON output

[
    {
      "GERMANY": "Berlin University of the Arts",
      "FRANCE": "Berlin University of the Arts",
      "UK": "Berlin University of the Arts",
      "NETHERLANDS": "Berlin University of the Arts"
    },
    {
      "GERMANY": "Dresden University of Technology",
      "FRANCE": "Dresden University of Technology",
      "UK": "Dresden University of Technology",
      "NETHERLANDS": "Dresden University of Technology"
    },
....
]

Now I need to modify the above to the below JSON structure.

{ 
"GERMANY": [
   "Berlin University of the Arts",
   "Dresden University of Technology",
   ...
],
"FRANCE": [...],

... so on
}

How can this be done, Please help

0

2 Answers 2

1

You can use reduce() to do it

let data =[
    {
      "GERMANY": "Berlin University of the Arts 1",
      "FRANCE": "Berlin University of the Arts 2",
      "UK": "Berlin University of the Arts 3",
      "NETHERLANDS": "Berlin University of the Arts 4"
    },
    {
      "GERMANY": "Dresden University of Technology 11",
      "FRANCE": "Dresden University of Technology 12",
      "UK": "Dresden University of Technology 13",
      "NETHERLANDS": "Dresden University of Technology 14"
    }
]

let result = data.reduce((a,v) => {
  Object.keys(v).forEach(k => (a[k] = a[k]??[]).push(v[k]))
  return a
},{})

console.log(result)

Sign up to request clarification or add additional context in comments.

Comments

0

You can use reduce to group data by keys

const input = [
    {
      "GERMANY": "Berlin University of the Arts",
      "FRANCE": "Berlin University of the Arts",
      "UK": "Berlin University of the Arts",
      "NETHERLANDS": "Berlin University of the Arts"
    },
    {
      "GERMANY": "Dresden University of Technology",
      "FRANCE": "Dresden University of Technology",
      "UK": "Dresden University of Technology",
      "NETHERLANDS": "Dresden University of Technology"
    },
]

const output = input.reduce((result, item) => {
   for(const key in item) {
      if(!result[key]) {
         result[key] = []
      }
      result[key].push(item[key]);
   }
   return result;
}, {})

console.log(output);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.