脚本不会向我的变量添加数据

时间:2012-04-27 01:26:58

标签: javascript

我使用ajax请求返回json编码。

现在返回数据如下:

 {"24": {"24":["205", "22", "1", "1", "0", "0"]}};

我试图添加到:

///global set
var data = {"24":{"16":["172","22","1","1","0","0"],"15":["160","22","1","1","0","0"]}};

问题是 - 我的尝试不是添加到变量。这是我的剧本:

var result = {24: {24:[205, 22, 1, 1, 0, 0]}}; //return data test
var obj = {}
for ( var key in result ){              
if ( result.hasOwnProperty( key ) ) {
    // If the key already exists
    if ( data[ key ] === result[ key ] ) {

        // Empty the temporary object
        obj = {}
        // Loop through the subkeys
        for ( var subkey in result[ key ] ) {              
            if ( result[ key ].hasOwnProperty( [ subkey ] ) ) {

                // Fill in the temporary object
                obj[ subkey ] = result[ key ][ subkey ]
            }
        }

        // Add the new object to the original object
        data[ key ] = obj
    }

    // If the key doesn't exist, do it normally
    else {
        data[ key ] = result[ key ]
       }
    }
}
obj = null

//show change
 console.log(data); 

在此代码运行后,我检查了数据,并且没有新添加的数据。任何人都可以看到错误在哪里/为什么不插入数据?

1 个答案:

答案 0 :(得分:1)

试试这个:

var data = {"24":{"16":["172","22","1","1","0","0"],"15":["160","22","1","1","0","0"]}};
var result = {"24": {"24":["205", "22", "1", "1", "0", "0"]}};

function forEach(o,cb){
    for(var i in o){
        if (o.hasOwnProperty(i)){
            cb(i);
        }
    }
}

forEach(result,function(key){
    if (!data[key]) data[key]={};
    forEach(result[key],function(subkey){
        if (!data[key][subkey]) data[key][subkey]=[];
        forEach(result[key][subkey],function(i){
            data[key][subkey].push(result[key][subkey][i]);
        });
    });
});

console.log(data);

演示: http://jsfiddle.net/363uy/