gpt4 book ai didi

javascript - 创建多级 JSON 字符串

转载 作者:行者123 更新时间:2023-11-29 18:29:47 26 4
gpt4 key购买 nike

我想用JS创建一个多级的JSON字符串。

场景

3 个国家有 5 个祖父和 3 个 child ,祖父也有 3 个 child 和 5 个 friend 。

我从如下所示的外部 JSON 文件获取数据。

 {"countries":[
{
"name":"USA",

"grandfathers":[
{
"gFName":"Steve",
"grandfathersKid":[
{
"gFKName": "Linda",
"kid": [{
"name": "Steve JR",
"friends": [{
"name": "Kriss|John|Martin|Steven"
}]
}
]
}

]
}
]
}
]}

现在我想在一个新的 JSON 列表中存储一些国家以及他们的亲戚和 friend ,该列表看起来与外部 json 文件中的列表完全一样。我打算稍后在脚本中使用这个“自制”列表。

我最初的 react 是

var tree = new Array();

tree = {};


var countries = new Array();

countries[0] = "canada";
countries[1] = "USA";
countries[2] = "Mexico";
countries[0][0] = "Steve"; //Lives in Canada
countries[0][0][0] = "Linda"; //Daughter of Steve
countries[0][0][0][0] = "Steve JR"; // Kid of Linda
countries[0][0][0][0][0] = "Kriss"; //Steves Friend
...


$.each(countries...function(index, value){
tree[index].country = value;

$.each(grandfathers...function(key, value){
tree[index].country[key].grandfather = value;

}

等等,但这并没有给我想要的结果。我究竟做错了什么?有比什么都拿走更有效的方法吗?

第三次编辑...

最佳答案

这是您想要做的事情吗?

var countries = $.map(oldCountries || [], function(country) {
return {
name: country.name,
people: $.map(country.grandfathers || [], function(gpa) {
return {
name: gpa.gFName,
children: $.map(gpa.grandfathersKid || [], function(parent) {
return {
name: parent.gFKName,
children: $.map(parent.kid || [], function(kid) {
return {
name: kid.name,
friends: kid.friends
};
})
};
})
};
})
};
});

我不确定如何处理 friends 节点。应该将其标准化为更有用的东西,还是您不想管它?

Fiddle演示了该技术。

关于javascript - 创建多级 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9533207/

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