1

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.

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

3 Comments

Upvoting this, because you did a sort, instead of assuming that you will get the correct order from the server.
@Mohammad: Its a good solution but found one issue. I add some more keys to each object like this for(let e of data) { Object.assign(e, {ip: "", port: 22, user: "", password: "", "device-type": "linux"}); } but its not reflecting along with other two keys in each nested and parent object.
@subhra_user Yes, you are right, I edited the script, and you can check it out now.
0

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);

2 Comments

We dont need next-hop in last object.
i updated the script

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.