获取对象的对象在数组中

时间:2016-04-28 07:51:44

标签: jquery arrays object

我有一个

数组
[{
    "39195": {
        "name": "Introduction",
        "lessons": [{
            "name": "A",
            "duration": "(05:30)",
            "movieName": "Why+Learn+ActionScript%3F"
        }, {
            "name": "About the Included Sample Scripts",
            "duration": "(03:49)"
        }, ]
    },
    "39196": {
        "name": "Introduction2",
        "lessons": [{
            "name": "B",
            "duration": "(05:30)",
            "movieName": "Why+Learn+ActionScript%3F"
        }, {
            "name": "About the Included Sample Scripts",
            "duration": "(03:49)"
        }, ]
    },
    "39197": {
        "name": "Introduction3",
        "lessons": [{
            "name": "C",
            "duration": "(05:30)",
            "movieName": "Why+Learn+ActionScript%3F"
        }, {
            "name": "About the Included Sample Scripts",
            "duration": "(03:49)"
        }, ]
    }
}]

我如何获得[Introduction,Introduction2,Introduction3]

的值数组

2 个答案:

答案 0 :(得分:1)

您可以使用 Object.keys() map()

var arr = [{
  "39195": {
    "name": "Introduction",
    "lessons": [{
      "name": "A",
      "duration": "(05:30)",
      "movieName": "Why+Learn+ActionScript%3F"
    }, {
      "name": "About the Included Sample Scripts",
      "duration": "(03:49)"
    }]
  },
  "39196": {
    "name": "Introduction2",
    "lessons": [{
      "name": "B",
      "duration": "(05:30)",
      "movieName": "Why+Learn+ActionScript%3F"
    }, {
      "name": "About the Included Sample Scripts",
      "duration": "(03:49)"
    }]
  },
  "39197": {
    "name": "Introduction3",
    "lessons": [{
      "name": "C",
      "duration": "(05:30)",
      "movieName": "Why+Learn+ActionScript%3F"
    }, {
      "name": "About the Included Sample Scripts",
      "duration": "(03:49)"
    }]
  }
}];

var res = Object.keys(arr[0]) // get get object keys for iteration
  .map(function(v) { // iterate over the array and retrieve needed property
    return arr[0][v].name // get name property from inner object
  });

document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>');

答案 1 :(得分:0)

这样就可以了。将a =设置为json数据

var names = [];
for (var key in a[0]) {
  if (a[0].hasOwnProperty(key)) {
    alert("prop: " + key + " value: " + a[0][key]['name']);
    names.push(a[0][key]['name']);
  }
}

如果它确实是一个数组,那么你可以添加另一个循环来遍历数组。