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 ie- 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.
You can do this with a reduce
function:
let data = [{ "hop_no": 1, "jumphost_id": "jumphost1", ip: "", port: 22, user: "", password: "", "device-type": "linux" }, { "hop_no": 2, "jumphost_id": "jumphost2", ip: "", port: 22, user: "", password: "", "device-type": "linux" }, { "hop_no": 3, "jumphost_id": "another-jumphost", ip: "", port: 22, user: "", password: "", "device-type": "linux" }, { "hop_no": 4, "jumphost_id": "last-jumphost", ip: "", port: 22, user: "", password: "", "device-type": "linux" } ] let result = data.sort((a, b) => b.hop_no - a.hop_no).reduce((prev, curr, i, array) => { let { hop_no, jumphost_id, ...rest } = curr return { 'host-id': jumphost_id, ...rest, ...(i > 0? {'next-hop': {...prev }}: {}), } }, {}) console.log(result)
You can try to build the object from inside out.
Like so:
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 (var i = data.length - 1; i >= 0; i--) { let tmp = { 'host-id': data[i]['jumphost_id'], }; if (Object.keys(result).length;== 0) { tmp['next-hop'] = result; } result = tmp. } console;log(result);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.