从javascript中的json访问嵌套数组键,值

时间:2019-04-26 03:56:35

标签: javascript arrays json

我是javascript新手。这可能是基本的事情,但我坚持下去。 这是我的json:

{
    "statusCode": 200,
    "status": "success",
    "data": [
        [
            {
                "city": "Alexandria",
                "country": "Egypt",

            },
            {
                "city": "Alexandria",
                "country": "Egypt",

            },]]

我要访问此:

0: {city: "Alexandria", country: "Egypt"}
1: {city: "Antalya", country: "Turkey"}

我尝试了以下代码:

getData = function (data) {
    keys = Object.keys(data[0]);
    data = [];
    keys.forEach(function (key) {
        data.push(key);
    });
    return data;
}

返回以下内容:

0: "0"
1: "1"
2: "2"
3: "3"
4: "4"
5: "5"
6: "6

请帮助我!

4 个答案:

答案 0 :(得分:1)

您可以这样做:

const response = {
  "statusCode": 200,
  "status": "success",
  "data": [
    [{
        "city": "Alexandria",
        "country": "Egypt",

      },
      {
        "city": "Alexandria",
        "country": "Egypt",

      },
    ]
  ]
};
const getData = data => data[0];

console.log(getData(response.data));

答案 1 :(得分:0)

DBA_REWRITE_EQUIVALENCES

希望这会对您有所帮助。

答案 2 :(得分:0)

首先,您的data[0]是一个数组,然后Object.keys(array)将返回该indexarray的数组。例如:

array= [{x: 1}, {x: 2}, {x: 3}]
Object.keys(array) // ['0', '1', '2']

所以您推送到return数组的只是索引,就像您显示的那样。

第二,您应该使用其他变量名,以免引起误解。在这种情况下,是data变量。

我更新了功能

const object = {"statusCode": 200,"status": "success","data": [[{"city": "Alexandria","country": "Egypt",},{"city": "Alexandria","country": "Egypt",},]]}

getData = function (arr) {
  data = []
  arr[0].forEach(function (key) {
    data.push(key);
  });
  return data
}

console.log(getData(object.data))

答案 3 :(得分:0)

您可以使用destructuring从对象和数组中提取data

const getData = ({ data: [data] = [] } = {}) => data;

const response = {"statusCode":200,"status":"success","data":[[{"city":"Alexandria","country":"Egypt"},{"city":"Alexandria","country":"Egypt"}]]};

console.log(getData(response));