Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

272
Views
Transform keys to values, values to keys in json object using typescript

Im trying to swap key to values, values to key, but could not find right solution using javascript/typescript.

  course =  
  [ 
   { 
     "name" : "John",
     "course" : ["Java", "Python"]
   },
   { 
     "name" : "Michel",
     "course" : ["Java", "Python", "Ruby"]
   }
   ]

I want the result json is like below:

  result = [
   {
     "course" : "Java",
     "name" : ["John", "Michel"]

   }, 
   {
     "course" : "Python",
     "name" : ["John", "Michel"]
   },
   {
     "course" : "Ruby",
     "name" : ["Michel"]
   }

   ]
about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Here is a JS solution. I'm grouping using reduce to get this intermediate object

{
  Java: {
    course: "Java",
    name: ["John", "Michel"]
  },
  Python: {
    course: "Python",
    name: ["John", "Michel"]
  },
  Ruby: {
    course: "Ruby",
    name: ["Michel"]
  }
}

Then I'm calling Object.values on this intermediate object to the values array as you needed

const course =  [    {      "name" : "John",     "course" : ["Java", "Python"]   },   {      "name" : "Michel",     "course" : ["Java", "Python", "Ruby"]   }   ]

const result = Object.values(course.reduce((acc,{name,course}) => {
  course.forEach(c => {
    acc[c]??={course:c,name:[]}
    acc[c].name.push(name)
  })
  return acc
},{}))

console.log(result)

about 4 years ago · Santiago Trujillo Report

0

const course = [{
    name: 'John',
    course: ['Java', 'Python'],
  },
  {
    name: 'Michel',
    course: ['Java', 'Python', 'Ruby'],
  },
]

const temp = course.reduce((acc, value) => {
  value.course.forEach(item => {
    if (!acc[item]) {
      acc[item] = []
    }

    acc[item].push(value.name)
  })

  return acc
}, {})

const result = Object.entries(temp).reduce((acc, [course, name]) => {
  acc.push({
    course,
    name,
  })

  return acc
}, [])

console.log(result)

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!