{"profit_center" :
{"branches":
[
{"branch": {"work_order":"1","cutover":"1","site_survey":"1","branch_number":"3310","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"1","site_survey":"1","branch_number":"3311","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"0","site_survey":"1","branch_number":"3312","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"1","site_survey":"1","branch_number":"3313","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"0","site_survey":"1","branch_number":"3314","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"1","site_survey":"1","branch_number":"3315","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}}
],
"profit_center_name":"Alabama"}}我试着通过这个在ajax中访问它,
data.profit_center //data here is the ajax variable e.g. function(data)或通过此data["profit_center"]
但没那么走运
如何正确访问这个javascript对象。?
顺便说一句,上面的代码来自console.log(data)
编辑:
来自console.log(data.profit_center)和console.log(data["profit_center"])的结果未定义
发布于 2014-05-02 19:44:49
首先解析您的数据,如果您还没有这样做的话。
例如,您可以像这样访问每个branch_number:
var branches = data.profit_center.branches;
for (var i = 0, l = branches.length; i < l; i++) {
console.log(branches[i].branch.branch_number);
}总之,profit_center是一个对象,而branches是一个对象数组。数组中的每个元素都包含一个包含多个键的分支对象。循环遍历branches数组,对于每个元素,使用键名称访问内部的分支对象以获取值。
利润中心名称可以通过访问profit_center对象上的profit_center_name键找到:
console.log(data.profit_center.profit_center_name); // Alabama您甚至可以使用新的函数数组方法来查询数据,并只提取需要的分支。在这里,我使用filter拉取那些purchase_order等于2的对象。请注意,JSON中的数值是字符串,而不是整数。
var purchaseOrder2 = branches.filter(function (el) {
return el.branch.purchase_order === '2';
});发布于 2014-05-02 19:48:27
您可以将data放在一个变量中,如下所示
var json = data
你可以像这样访问profit_center
alert(json.profit_center);
alert(json.profit_center.profit_center_name); //Alabama
for(var i =0 ;i<json.profit_center.branches.length;i++){ alert(json.profit_center.branches[i]); }
发布于 2014-05-02 19:57:23
好了,我已经找到了为什么它是未定义的,它是一个json对象,所以我需要先解析它,然后才能像javascript对象一样访问它。
var json = JSON.parse(data);那就是这样了。
https://stackoverflow.com/questions/23427214
复制相似问题