gpt4 book ai didi

javascript - 尝试访问 JSON 数组中的 key

转载 作者:行者123 更新时间:2023-12-03 00:58:27 25 4
gpt4 key购买 nike

我正在尝试将 Chart JS 集成到项目中。我有一些使用以下内容通过 Ajax 返回的 JSON 数据:

$(".symptom-graph").each(function(){
Tygh.$.ceAjax(
'request',
fn_url('symptom_tools.ajax_symptom_graph'),
{
data:{
symptom_ids: $(this).data('symptom-id')
},
callback: function(data) {
$(".symptom-graph").each(function(){
if($(this).data('symptom-id') == data['symptom_ids'])
{
//TODO: load up graph stuff here
$(this).html(data['graph_data']);
}
});
}

}
);
});

上面的代码返回以下 JSON 数据:

[{
"x": "0",
"y": "35"
}, {
"x": "1",
"y": "6"
}, {
"x": "2",
"y": "3"
}, {
"x": "3",
"y": "11"
}, {
"x": "4",
"y": "2"
}]

我试图访问数组中的每个项目并提取 X 或 Y 坐标,以便 Chart JS 脚本中的 data: [] 数组包含每个项目。

我尝试了以下方法来访问 Y 或 X 坐标:

数据['graph_data']['0']['y']

数据['graph_data'][0]['y']

数据['graph_data']['y']

数据['graph_data'][0]

也不知道如何循环每个。

任何指导/解决方案都会有帮助,谢谢。

最佳答案

您也可以使用$.each()函数,并使用jQuery.parseJSON(YourJsonDataSet)

var xArray = [];

$(document).ready(function(){
var data = jQuery.parseJSON('[{"x": "0","y": "35"}, {"x": "1","y": "6"}, {"x": "2","y": "3"}, {"x":"3","y": "11"}, {"x": "4","y": "2"}]');

$.each(data,function(index, value){
console.log("X - "+ value.x + " and Y - " +value.y)
xArray.push(value.x);
});

alert(xArray.join())

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

关于javascript - 尝试访问 JSON 数组中的 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52719700/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com