{"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"])
的结果未定义
答案 0 :(得分:0)
首先解析您的数据,如果您还没有这样做。
例如,您可以访问每个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_name
对象上的profit_center
键找到利润中心名称:
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';
});
答案 1 :(得分:0)
您可以将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]);
}
答案 2 :(得分:0)
好的,我已经找到了为什么它是未定义的,它是一个json对象所以我需要解析它才能像javascript对象一样访问它。
var json = JSON.parse(data);
那就是它。