获取每个嵌套级别的对象列表

时间:2017-05-19 08:49:59

标签: javascript jquery json firebase firebase-realtime-database

{
    "John Doe": {
        "Age": 18,
        "Gender": "M"
    },
    "Jane Doe": {
        "Age": 16,
        "Gender": "F"
    },
    "Steve Appleseed":{
        "Age": 21,
        "Gender": "M"
    }
}

使用JavaScript,我如何获得数组

var names = ["John Doe", "Jane Doe", "Steve Appleseed"];

如果它有用,我使用Firebase和JavaScript和jQuery PWA,我需要一个嵌套特定级别的所有对象名称的列表。

4 个答案:

答案 0 :(得分:4)

首先请注意,这与JSON无关。你拥有的是一个物体。因此,Object.keys将满足您的要求:

var obj = {
  "John Doe": {
    "Age": 18,
    "Gender": "M"
  },
  "Jane Doe": {
    "Age": 16,
    "Gender": "F"
  },
  "Steve Appleseed": {
    "Age": 21,
    "Gender": "M"
  }
}

var keys = Object.keys(obj);
console.log(keys);

console.log(obj[keys[0]]["Age"]); // John Doe's age

答案 1 :(得分:1)

您可以使用Object.keys(obj)

有关详细信息,请参阅here



var obj = {
    "John Doe": {
        "Age": 18,
        "Gender": "M"
    },
    "Jane Doe": {
        "Age": 16,
        "Gender": "F"
    },
    "Steve Appleseed":{
        "Age": 21,
        "Gender": "M"
    }
};

var result = Object.keys(obj);

console.log(result);




答案 2 :(得分:0)

试试这个

var obj = {
    "John Doe": {
        "Age": 18,
        "Gender": "M"
    },
    "Jane Doe": {
        "Age": 16,
        "Gender": "F"
    },
    "Steve Appleseed":{
        "Age": 21,
        "Gender": "M"
    }
}

    console.log(Object.keys(obj))

答案 3 :(得分:0)

您可以使用object.keys(); 有关详细信息,请查看https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

t = {
    "John Doe": {
        "Age": 18,
        "Gender": "M"
    },
    "Jane Doe": {
        "Age": 16,
        "Gender": "F"
    },
    "Steve Appleseed":{
        "Age": 21,
        "Gender": "M"
    }
}

Object.keys(t);