0

我使用 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); 

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

4

1 回答 1

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/

于 2012-04-27T02:12:01.117 回答