0

我有一个包含元素的数组,

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

我不想要纽约和墨西哥的基本水平。我怎么做?

4

2 回答 2

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"
    ]
}
于 2012-06-07T11:14:09.310 回答
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));​

演示:http: //jsfiddle.net/7PpEY/

我忽略了所有你不关心的领域。我忽略了这样一个事实,即在您的数据中,“Persons”对象的“Count”为 10,即使内部数组中只有两个人。你的函数是递归的,但我认为没有必要。

于 2012-06-07T11:43:46.440 回答