gpt4 book ai didi

javascript - 获取 JSON 输入并将其存储到数组中 (javascript)

转载 作者:行者123 更新时间:2023-12-02 19:40:33 26 4
gpt4 key购买 nike

我有一个 JSON 输入

{
"Categories": {
"Facets": [{
"count": 1,
"entity": "Company",
"Company": [{

"entity": "Ford Motor Co",

"Ford_Motor_Co": [{
"count": 1,
"entity": "Ford"
}]
}]
}, {
"count": 4,
"entity": "Country",
"Country": [{

"entity": "Germany",
"Germany": [{
"count": 1,
"entity": "Germany"
}],
"currency": "Euro (EUR)"
}, {

"entity": "Italy",
"Italy": [{
"count": 1,
"entity": "Italy"
}],
"currency": "Euro (EUR)"
}, {

"entity": "Japan",
"Japan": [{
"count": 1,
"entity": "Japan"
}],
"currency": "Yen (JPY)"
}, {

"entity": "South Korea",
"South_Korea": [{
"count": 1,
"entity": "South Korea"
}],
"currency": "Won (KRW)"
}]
}, {
"count": 5,
"entity": "Persons",
"Persons": [{
"count": 2,
"entity": "Dodge"
}, {
"count": 1,
"entity": "Dodge Avenger"
}, {
"count": 1,
"entity": "Major League"
}, {
"count": 1,
"entity": "Sterling Heights"
}]
}]

}
}

我需要将每个级别中实体的值获取到数组中..

[Company, Ford Motor Co, Ford, ....... , Sterling Heights]

我能够通过代码完成第一关

for (var k in h.Categories.Facets)
{

alert(h.Categories.Facets[k].entity);

}

如何通过内部级别获取实体的值?

最佳答案

您应该对每个实体执行 foreach。如果您知道有多少层,则可以嵌套循环。如果不是 - 可能应该使用递归函数。

编辑

递归函数:

function getEntities(ent)
{
alert(ent);
for (var l in ent)
{
getEntities(ent[l].entity);
}
}

然后使用:

for (var k in h.Categories.Facets)
{
getEntities(h.Categories.Facets[k]);
}

祝你好运!

关于javascript - 获取 JSON 输入并将其存储到数组中 (javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10439083/

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