未使用 Javascript 获取嵌套对象的所有键

Not getting all the keys of nested object using Javascript

我正在尝试使用 Javascript 获取一个嵌套对象的所有键,但根据我的代码,它没有按预期工作。我在下面解释我的代码。

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

这里我没有得到 service 数组中的键。我需要使用 Javascript.

搜索一个嵌套对象中存在的所有键

你可以做到这一点

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

您要求它与作为数组的“服务”键一起使用,但您的代码明确检查类型,如果它是数组,它就会忽略它。这是调整后也适用于数组的代码。

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