在javascript中为knockout observableArray([])创建一个对象数组

时间:2016-10-02 02:19:19

标签: javascript knockout.js

我试图创建以下" OutputArray"来自" InputObject"。我创建了一个函数getdata()来转换这两个对象。 当我在chrome中将这些对象写入控制台时,它们的显示方式略有不同,屏幕截图位于下方。

OuputObect:(这是我想要的输出)

{
            "id" : "1",
            "name" : "Name the color",
            "q" : "what is the color white in HTML",
            "a" : "255 255 255",
            "video" : "http://aws.asdfsadf.com/something.mkv",
            "images" : {
                "title" : "White Image",
                "url" : "http://aws.asdfsdf.com/image.jpg"
                }
        },
        {
            "id" : "2",
            "name" : "Name the color",
            "q" : "what is the color black in HTML",
            "a" : "0 0 0",
            "video" : "http://aws.asdfsadf.com/something.mkv",
            "images" : {
                "title" : "White Image",
                "url" : "http://aws.asdfsdf.com/image.jpg"
        }
}

OutputObject应该像这样出现在chrome中: console.log(OutputObject)

Correct output

相反它看起来像这样: console.log(getdata(InputObject))

Incorrect output

InputObject:(这是FireDB提供数据的方式)

{
        "1" : {
            "name" : "Name the color",
            "q" : "what is the color white in HTML",
            "a" : "255 255 255",
            "video" : "http://aws.asdfsadf.com/something.mkv",
            "images" : {
                "title" : "White Image",
                "url" : "http://aws.asdfsdf.com/image.jpg"
                }
        },
        "2" : {
            "name" : "Name the color",
            "q" : "what is the color black in HTML",
            "a" : "0 0 0",
            "video" : "http://aws.asdfsadf.com/something.mkv",
            "images" : {
                "title" : "White Image",
                "url" : "http://aws.asdfsdf.com/image.jpg"
                }
        }

    }

getdata()函数...

function getdata(data){

    var array = [];

    for (var key in data) {

        var arrayObject = {};

        // skip loop if the property is from prototype
        if (!data.hasOwnProperty(key)) continue;

        var obj = jsondata.questions[key];
        for (var prop in obj) {
            // skip loop if the property is from prototype
            if(!obj.hasOwnProperty(prop)) continue;
            arrayObject[prop] = obj[prop];
            }

        arrayObject["id"] = key;
        array.push(arrayObject)
    }
return array;
}

1 个答案:

答案 0 :(得分:0)

事实证明两个阵列都是相同的,它们在chrome中的显示方式不同。

我的问题是我正在调用ko.observableArray([OutputObject])

(带方括号)

而不是:

ko.observableArray(的GetData(OutputObject));