我有一个包含元素的数组,
var input=[
{
"count": 1,
"entity": "Company",
"Company": [
{
"sector": "Consumer, Cyclical",
"ticker": "NWY",
"entity": "New York & Co",
"New_York_&_Co": [
{
"count": 1,
"entity": "New York"
}
],
"type": "SCap"
}
]
},
{
"count": 1,
"entity": "Country",
"Country": [
{
"region": "North Americas",
"index": "MEXICO IPC INDEX",
"Mexico": [
{
"count": 1,
"entity": "Mexico"
}
],
"entity": "Mexico",
"currency": "Peso (MXN)"
}
]
},
{
"count": 2,
"entity": "Persons",
"Persons": [
{
"count": 1,
"entity": "Edwin Garay"
},
{
"count": 1,
"entity": "Rosa"
}
]
}];
我正在尝试订购此数据的输出。我想显示像
这样的值Company-New York & Co, Country-mexico, Persons-Edwin Garay,Rosa
我不需要最后一级的数据......我写了一个函数,
function generateTree(input) {
if (input == undefined) {
return;
}
else {
for ( var i = 0; i < input.length; i++) {
if(entityName1!=input[i].entity)
{
entityName = input[i].entity;
entityName1 = input[i].entity;
entityName = entityName.replace(/ /g, "_");
alert(entityName);
}
if (input[i][entityName] != undefined) {
generateTreeHTML(input[i][entityName]);
}
}
}}
上面的脚本将打印输出
Company-New York & Co, NewYork , Country-mexico,mexico, Persons-Edwin Garay,Rosa
我不想要纽约和墨西哥的基准水平。我该怎么做?
答案 0 :(得分:0)
您的数据结构对我来说似乎过于复杂。 count
字段特别无用。你不能修改你的数据结构吗?
var data = {
"companies": [{
"name": "New York & Co",
"sector": "Consumer, Cyclical",
"ticker": "NWY",
"type": "SCap"
}],
"countries": [{
"name": "Mexico",
"region": "North Americas",
"index": "MEXICO IPC INDEX",
"currency": "Peso (MXN)"
}],
"people": [
"Gustavo",
"Rosa"
]
}
答案 1 :(得分:0)
以下产生您要求的输出:
function generateTree(input) {
var i,
j,
currentEntity,
currentEntityType,
output = "";
for (i=0; i<input.length; i++) {
if (i > 0) output += ", ";
currentEntity = input[i];
currentEntityType = currentEntity.entity;
output += currentEntityType + "-";
for (j=0; j<currentEntity[currentEntityType].length; j++){
if (j > 0) output += ",";
output += currentEntity[currentEntityType][j].entity;
}
}
return output;
}
alert(generateTree(input));
我忽略了你不关心的所有领域。我忽略了这样一个事实,即在你的数据中,“人物”对象的“计数”是10,即使内部数组中只有两个人。你的函数是递归的,但我认为没有必要。