Javascript - 如何通过动态忽略其父键来获取JSON Root Children Key?

时间:2018-05-08 01:27:32

标签: javascript json object foreach

代码:

const jsonFile = require("data.json")

// Get the KEY of the JSON but not the Data (failed to get Root Children Key, only get the Parent Key)
var getKey = Object.keys(jsonFile);

// Declared for do matching purpose
var matchData = "country"; 

// using for each loop and try to get all the key to do matching
for(var count in getKey){

    // get the key and do matching
    if(getkey[count]==matchData){
        //Do Something  
    }

}

JSON文件

{
 "class" : {
   "id" : "abc123456",
   "name" : "Programming Class"
 },
 "address" : {    
   "postcode" : "30100",
   "city" : "IPOH",
   "state" : "PERAK",
   "country" : "MALAYSIA"
 }
}

我试图通过动态忽略其父键来获取JSON Root Children Key。

对于此示例,我使用for each loop并尝试循环访问JSON文件并获取其所有密钥,但是我只能获得class父密钥address

我的欲望输出:

我想要的是获取classaddressid, name, postcode, city, state, country的所有儿童密钥,并for each loop使用它们与我声明的matchData匹配。

如何实现这一目标?

注意:(请参阅下面的JSON)

  1. 我一直想获得 root Children Key ,例如下面的JSON文件。我希望获得code, number, first, last, postcode, city, state, country并使用它们进行匹配。

  2. 试图获取数据,例如abc, 123456, Programming, Class, 30100, IPOH, PERAK, MALAYSIA,但我想获得的是code, number, first, last, postcode, city, state, country

  3. 我的注释示例JSON

    {
        "class": {
            "id": {
                "code": "abc",
                "number": "123456"
            },
            "name": {
                "first": "Programming",
                "last": "Class"
            },
        },
        "address": {
            "postcode": "30100",
            "city": "IPOH",
            "state": "PERAK",
            "country": "MALAYSIA"
        }
    }
    

1 个答案:

答案 0 :(得分:0)

您可以使用以下命令自动查找根对象的嵌套属性:



var json = {
    "class": {
        "id": {
            "code": "abc",
            "number": "123456"
        },
        "name": {
            "first": "Programming",
            "last": "Class",
            "code": "234567"
        },
    },
    "address": {
        "postcode": "30100",
        "city": "IPOH",
        "state": "PERAK",
        "country": "MALAYSIA"
    }
};

function parseKeys(keys, obj) {
  return Object.keys(obj).reduce(function (keys, key) {
    if (typeof obj[key] !== 'object') {
      return keys.concat(key);
    }
    
    return parseKeys(keys, obj[key]);
  }, keys);
}

// Keys with duplicates
var duplicateKeys = parseKeys([], json);

// Remove duplicates
var uniqueKeys = Array.from(new Set(duplicateKeys));

console.log(duplicateKeys, uniqueKeys);