将结果添加到对象

问题描述:

我有一个小函数,它将返回的结果添加到对象列表中,但是我遇到的问题是,如果存在某个重复,它将不会允许它 - 但有一些方面发生重复,而其他这不方面...将结果添加到对象

我会解释有更好的例子:

var data = {"24":{"16":["172"],"15":["160"]}} 

此数据表转换为:

var data = {"X":{"Y":["id"],"Y":["id"]}}; 

现在即时通讯试图插入NE这样的W数据:

for(var key in result){    
     if(result.hasOwnProperty(key)){ 
     data[key] = result[key];  
     } 
    } 

如果你考虑网格坐标,在我的对象列表,Y不能在相同的X复制和X完全无法被复制。

这是“结果”,即时通讯试图插入的示例数据:

{24: {13:[187]}} 

因此转向VAR数据:

var data = {"24":{"16":["172"],"15":["160"],"13":["187"]}}; 

是否有任何人知道我可以实现的重复检查我的循环?

+0

难道你不能在试图添加它之前测试'if(key in data)'或'if(data.hasOwnProperty(key))'吗? – RobG 2012-04-24 03:51:52

+0

,但是如果密钥变成数据,它将如何添加剩余的数据..例如..如果已经找到X,它仍然需要将Y [id]添加到已存在的X中 – Sir 2012-04-24 16:48:23

+0

我不知道在你想复制数据的情况下,当你不想复制数据时,我认为'in'可能会帮助你决定怎么做。 – RobG 2012-04-25 04:20:40

// Declare this temporary object we'll use later 
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 ] 
     } 
    } 
} 

// Now, to be tedious, let's free up the memory of the temporary object! 
obj = null 

像这样的东西应该工作。如果发生冲突,我重建内联对象,以便我可以将它添加回所有原始键和新键/值。

PS:最后一行只是为了好玩。

+0

谢谢你刚刚回答了一个问题,我即将要问的问题是释放内存:P! Spooky:P 我会试试这个脚本!谢谢 ! – Sir 2012-04-24 20:43:49