0

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.

5
  • Please take note that let jsonObj means you do not have JSON, you have a normal JS object. Commented May 17, 2022 at 7:25
  • 1
    In both places you are checking that the property you are currently handling is not instanceof Array - but service is an array? Commented May 17, 2022 at 7:30
  • add an else if(Array.isArray(value)) after the second if and inside that value.forEach(val => getNestedKeys(val, keys)) . someting like this? Commented May 17, 2022 at 7:31
  • 1
    What should happen if there are multiple items in the array? Commented May 17, 2022 at 7:35
  • in case need to remove duplicates from the final result [...new Set(result)] Commented May 17, 2022 at 7:38

2 Answers 2

1

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

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

1 Comment

Note: If there are multiple entries in the array, the key is added multiple times.
0

You are asking for it to work with "service" key which is an array, but your code explicitly checks type and if it's array it just ignores it. Here is the code adjusted to work with array too.

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) {
      data.forEach(value => {
          getNestedKeys (value, keys);
      });
  }

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

console.log('result', result);

Comments

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.