从嵌套对象中选择Key

时间:2014-09-23 06:06:20

标签: javascript json

我有一个情况。我这里有一个对象,它嵌套在另一个里面,这里我要选择密钥。对象如下所示

var x={
    "_shards": {
        "total": 10,
        "successful": 5,
        "failed": 0
    },
    "_all": {
        "primaries": {
            "indexing": {
                "index_total": 4,
                "index_time_in_millis": 5,
                "index_current": 0,
                "delete_total": 0,
                "delete_time_in_millis": 0,
                "delete_current": 0
            }
        },
        "total": {
            "indexing": {
                "index_total": 4,
                "index_time_in_millis": 5,
                "index_current": 0,
                "delete_total": 0,
                "delete_time_in_millis": 0,
                "delete_current": 0
            }
        }
    },
    "indices": {
        "get56_name": {
            "primaries": {
                "indexing": {
                    "index_total": 4,
                    "index_time_in_millis": 5,
                    "index_current": 0,
                    "delete_total": 0,
                    "delete_time_in_millis": 0,
                    "delete_current": 0
                }
            },
            "total": {
                "indexing": {
                    "index_total": 4,
                    "index_time_in_millis": 5,
                    "index_current": 0,
                    "delete_total": 0,
                    "delete_time_in_millis": 0,
                    "delete_current": 0
                }
            }
        }
    }
}

如何选择密钥,即" get56_name"作为答案。我不想要价值,我想选择关键怎么才能得到它?

2 个答案:

答案 0 :(得分:1)

这将返回像"get56_name"

这样的键数组中的第一个键
Object.keys(x["indices"])[0]

希望这就是你所要求的

答案 1 :(得分:1)

试试这个:

var your_variable = Object.keys(x.indices)[0];