I am trying to convert one array of object to one nested object structure using Javascript but the result is not coming as expected. I am explaining my code below.
let data = [
{
"hop_no": 1,
"jumphost_id": "jumphost1"
},
{
"hop_no": 2,
"jumphost_id": "jumphost2"
},
{
"hop_no": 3,
"jumphost_id": "another-jumphost"
},
{
"hop_no": 4,
"jumphost_id": "last-jumphost"
}
]
let result ='';
for(let i = 0; i< data.length; i++) {
const index = i+1;
const obj = data.find(o => o.name === index);
if(result === '' && !result['host-id']) {
result = {
"host-id": obj.jumphost_id,
"next-hop":{}
}
}else{
if(result['next-hop'] === '') {
result['next-hop'] = obj.jumphost_id
}
}
}
Here the array of object is given i.e- data and my expected structure is given below.
Expected result below.
{
"host-id": "jumphost1",
"next-hop": {
"host-id": "jumphost2",
"next-hop": {
"host-id": "another-jumphost",
"next-hop": {
"host-id": "last-jumphost",
}
}
}
}
Here the condition is when "hop_no": 1 the respective jumphost_id value will assign to host-id and will be the first key. after that the nested object structure will be formed in ascending order of hop_no value and the respective jumphost_id value will assign to next-hop key. Can anybody help me to design this structure using Javascript only.