gpt4 book ai didi

jQuery如何通过多个循环从json获取数据

转载 作者:行者123 更新时间:2023-12-01 07:45:30 26 4
gpt4 key购买 nike

我有这样的json数据http://pastebin.com/k3a5UNsL enter image description here当使用 json 格式化程序查看时,我想在 possible_persons 对象内使用 jquery 获取存储在对象上的数据。

我正在尝试循环数据,但很困惑如何获取数据名称、性别、地址等...... enter image description here enter image description here

当我使用此代码时

function build_possible_persons(result) {
var relationship = result['possible_persons'];
$.each(relationship, function(key, value) {
$.each(value, function(sec_key, sec_value) {
alert(sec_value);
});
});
}

我得到了第一个循环结果的alert值,如图0:25、3788825f48716e6c ....、[object]、[object]等....

如何循环访问其中的对象以获得我想要的值?我尝试一下

function build_possible_persons(result) {
var relationship = result['possible_persons'];
$.each(relationship, function(key, value) {
$.each(value, function(sec_key, sec_value) {
$.each(sec_key.names, function(third_key, third_value) {
alert(third_key);
});
});
});
}

或使用

alert(sec_key.names[0].display);

但运气不佳。我创建的代码没有显示任何结果。

请帮助查看我的代码中的缺陷。谢谢

最佳答案

使用 Array.prototype.map() 可以更简单

function build_possible_persons(result) {
var persons = result.possible_persons;
alert(persons.map(p => p.addresses ? p.addresses[0].display : 'N/A').join("\n"))
}

编辑:使用 arrow functions您可以像这样合并此人的数据:

function build_possible_persons(result) {
var persons = result.possible_persons;
var rows = persons.map(p => {
var address = p.addresses ? p.addresses[0].display : 'N/A';
var name = p.names ? p.names[0].display : 'N/A'
return name + ' ' + address;
});

alert(rows.join('\n'));
}

关于jQuery如何通过多个循环从json获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38938863/

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