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"]
}
]
CodePudding user response:
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)
CodePudding user response:
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)