Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Not getting all the keys of nested object using Javascript

I am trying to fetch all the keys of one nested object using Javascript but as per my code its not working as expected. I am explaining my code below.

let jsonObj = {
    "service":[
        {
            "name":"restservice",
            "device":"xr-1",
            "interface-port":"0/0/2/3",
            "interface-description":"uBot testing for NSO REST",
            "addr":"10.10.1.3/24",
            "mtu":1024
        }
    ],
    "person": {
    "male": {
      "name": "infinitbility"
    },
    "female": {
      "name": "aguidehub"
    }
  }
}

const getNestedKeys = (data, keys) => {
  if(!(data instanceof Array) && typeof data == 'object'){
    Object.keys(data).forEach(key => {
      keys.push(key);
      const value = data[key];
      if(typeof value === 'object' && !(value instanceof Array)){
         getNestedKeys(value, keys);
      }
   });
  }
  return keys
}
let result = getNestedKeys(jsonObj, []);

console.log('result', result);

Here I am not getting the keys present inside the service array. I need to search all the keys present inside one nested object using Javascript.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

you can do this

const readAllKeys = obj => {
  if(typeof obj !== 'object'){
    return []
  }
  if(Array.isArray(obj)){
    return obj.flatMap(readAllKeys)
  }
  
  return [...Object.keys(obj), ...Object.values(obj).flatMap(readAllKeys)]
}


let jsonObj = {
    "service":[
        {
            "name":"restservice",
            "device":"xr-1",
            "interface-port":"0/0/2/3",
            "interface-description":"uBot testing for NSO REST",
            "addr":"10.10.1.3/24",
            "mtu":1024
        }
    ],
    "person": {
    "male": {
      "name": "infinitbility"
    },
    "female": {
      "name": "aguidehub"
    }
  }
}

console.log(readAllKeys(jsonObj))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading