如何访问存储在Json对象中的数组?

时间:2015-09-29 05:59:34

标签: javascript json ajax rest

我这样的json回复,我希望从中得到所有项目名称。

我像往常一样迭代数组,但这里" d"不是数组。 我怎样才能得到结果:

{
    "d": {
    "results": [
        {
            "ProjectId": "696fcc7c-f355-e511-93f0-00155d008500",
            "ProjectName": "Payroll",
            "EnterpriseProjectTypeDescription": null,
            "EnterpriseProjectTypeId": null,
            "EnterpriseProjectTypeIsDefault": null
        },
        {
            "ProjectId": "696fcc7c-f355-e511-93f0-00155d008505",
            "ProjectName": "Permanant",
            "EnterpriseProjectTypeDescription": null,
            "EnterpriseProjectTypeId": null,
            "EnterpriseProjectTypeIsDefault": null
        }
    ]
    }
}

2 个答案:

答案 0 :(得分:3)

使用Array.prototype.map()

var names = myData.d.results.map(function(item){
    return item.ProjectName;
});

这将产生如下数组:

["Payroll", "Permanant"]

(假设myData是你问题中的对象)

答案 1 :(得分:1)

您可以使用 jsonObject.d.results 从响应中获取数组并使用 forEach() 来迭代数组



var res = {
  "d": {
    "results": [{
        "ProjectId": "696fcc7c-f355-e511-93f0-00155d008500",
        "ProjectName": "Payroll",
        "EnterpriseProjectTypeDescription": null,
        "EnterpriseProjectTypeId": null,
        "EnterpriseProjectTypeIsDefault": null
      }, {
        "ProjectId": "696fcc7c-f355-e511-93f0-00155d008505",
        "ProjectName": "Permanant",
        "EnterpriseProjectTypeDescription": null,
        "EnterpriseProjectTypeId": null,
        "EnterpriseProjectTypeIsDefault": null
      }
    ]
  }
};

res.d.results.forEach(function(v) {
  document.write(v.ProjectName + '<br>')
})
&#13;
&#13;
&#13;

如果您想将其作为数组使用,那么您可以使用 map()

&#13;
&#13;
var res = {
  "d": {
    "results": [{
      "ProjectId": "696fcc7c-f355-e511-93f0-00155d008500",
      "ProjectName": "Payroll",
      "EnterpriseProjectTypeDescription": null,
      "EnterpriseProjectTypeId": null,
      "EnterpriseProjectTypeIsDefault": null
    }, {
      "ProjectId": "696fcc7c-f355-e511-93f0-00155d008505",
      "ProjectName": "Permanant",
      "EnterpriseProjectTypeDescription": null,
      "EnterpriseProjectTypeId": null,
      "EnterpriseProjectTypeIsDefault": null
    }]
  }
};

var result = res.d.results.map(function(v) {
  return v.ProjectName;
})

document.write(JSON.stringify(result));
&#13;
&#13;
&#13;