0

这是我想要实现的目标。

我有以下 JSON 响应。我正在使用 $.getJSON 方法加载 JSON 数据并通过检查它是否为如下数组将其添加到集合中。

    {
    "r": [{
        "IsDefault": false,
        "re": {
            "Name": "Depo"            
        },
        "Valid": "Oct8, 2013",
        "Clg": [{
            "Name": "james",
            "Rate": 0.05
        }, {
            "Name": "Jack",
            "Rate": 0.55
       }, {
            "Name": "Mcd",
            "Rate": 0.01,
        }],
    },
    {
        "IsDefault": false,
        "re": {
            "Name": "Depo"
        },
        "Valid": "Oct8, 2013",
        "Clg": [{
            "Name": "james",
            "Rate": 0.05
        }, {
            "Name": "Jack",
            "Rate": 0.55
       }, {
            "Name": "Mcd",
            "Rate": 0.01,
        }],
    },
    {
        "IsDefault": false,
        "re": {
            "Name": "Depo"
        },
        "Valid": "Oct8, 2013",
        "Clg": [{
            "Name": "james",
            "Rate": 0.05
        }, {
            "Name": "Jack",
            "Rate": 0.55
       }, {
            "Name": "Mcd",
            "Rate": 0.01,
        }],
    }]
}

我将 loadFromJson1 和 loadFromJson2 函数上的 json 响应作为参数传递,如下所示。

var tablesResult = loadFromJson1(resultstest.r[0].Clg);
    loadFromJson1 = function (input) {
        if (_.isArray(input)) {
        alert("loadFromJson1: Inside array function");
            var collection = new CompeCollection();
            _.each(input, function (modelData) {
                collection.add(loadFromJson1(modelData));
            });
            return collection;
        }
        return new CompeModel({
            compeRates: loadFromJson2(input),
            compName: input.Name
        });
    };

    loadFromJson2 = function (input)
    // here is the problem, the 'input' is not an array object so it is not going to IF condition of the isArray method. Hence i am trying to convert into array object.
    {
        if (_.isArray(input)) {
            alert("loadFromJson2: Inside array function");
            //alert is not coming here though it is array
            var rcollect = new rateCollection();
            _.each(input, function (modelData) {
                rcollect.add(modelData);
            });
            return rcollect;
        }
    };

上面的代码我将 loadFromJson1 和 loadFromJson2 函数的 json 响应作为“输入”传递。isArray 仅在 loadFromJson1 函数上为真,并在 if 条件内发出警报,但未进入 loadFromJson2 函数,尽管我传递了相同的参数。

你能告诉我我在这里犯了什么错误吗?

4

1 回答 1

0

您的代码有点分散,并且函数 loadFromJson1 是重复的。还有一些对象没有发布在问题中。

但是,我确实创建了一个可以工作的小提琴;打印“内部数组函数”...

loadFromJson1 的简化版本在小提琴中工作:

loadFromJson1 = function (input) {
    var resArray = $.map(input, function (value, index) {
        return [value];
    });
    if (_.isArray(resArray)) {
        console.log("Inside array function");
    }
};
于 2013-10-18T11:13:47.427 回答