I am working on restructuring an incoming JSON object to utilize in a React component.
The JSON data that I'm receiving is stored in jsonData
. This is the current structure of my code:
const jsonData = {
"Jonas": {
"position": "CTO",
"employees": [{
"Sophie": {
"position": "VP Engineering",
"employees": [{
"Nick": {
"position": "Team Lead",
"employees": [{
"Pete": {
"position": "Backend Engineer",
"employees": []
}
},
{
"Barbara": {
"position": "Fronted Engineer",
"employees": []
}
}
]
}
},
{
"Melissa": {
"position": "Product Manager",
"employees": []
}
}
]
}
}]
}
}
const userList = [jsonData]
const formatData = list =>
list.map(item => {
let name, position, employees
for (let key in item) {
name = key
position = item[key].position
employees = item[key].employees ? item[key].employees : []
}
return {
name,
position,
employees: employees ? formatData(employees) : employees
}
})
console.log(formatData(userList))
I am attempting to assign a new id
to each object and transform the jsonData
into an array. The desired output should include the following -
[
{
"id": 0,
"name": "Jonas",
"position": "CTO",
"employees": [
{
"id": 1,
"name": "Sophie",
"position": "VP Engineering",
"employees": [
{
"id": 2,
"name": "Nick",
"position": "Team Lead",
"employees": [
{
"id": 3,
"name": "Pete",
"position": "Backend Engineer",
"employees": []
},
{
"id": 4,
"name": "Barbara",
"position": "Frontend Engineer",
"employees": []
}
]
},
{
"id": 5,
"name": "Melissa",
"position": "Product Manager",
"employees": []
}
]
}
]
}
]
How can I incorporate an id
for each object in the generated output?