我有一个
的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);
}
如何通过内层获取实体的值?
答案 0 :(得分:1)
你应该对每个实体做一个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]);
}
祝你好运!
答案 1 :(得分:1)
最常见的递归答案:
function getEntities(any) { var entities = []; if ('entity' in any) { entities.push(any.entity); } for (var prop in any) { if (any[prop] instanceof Object && any.hasOwnProperty(prop)) { entities.append(getEntities(any[prop])); } } return entities; } console.log(getEntities(h));
该行:
if (any[prop] instanceof Object && any.hasOwnProperty(prop)) {
保持数字/空值不受轰炸,而any.hasOwnProperty(prop)弥补了想要附加到Object原型的框架。
答案 2 :(得分:0)
一种方法是编写一个递归方法,接受一个数组并从中提取方法。
答案 3 :(得分:0)
根据建议,您可以使用递归函数遍历每个可能的嵌套组合:
var allEntities = [];
function getEntities(obj)
{
if (obj != null)
{
var entityName = obj["entity"];
alert(entityName);
if (entityName != null)
{
allEntities.push(entityName);
var adjName = entityName.replace(/ /gi, "_");
var entities = obj[adjName];
if (entities != null)
{
for (var e in entities)
{
var innerEntities = getEntities(entities[e]);
for (var inner in innerEntities)
allEntities.push(innerEntities[inner]);
}
}
}
}
}
for (var k in h.Categories.Facets)
{
alert(h.Categories.Facets[k].entity);
getEntities(h.Categories.Facets[k]);
}
alert(allEntities.length);