0

返された結果をオブジェクトのリストに追加する小さな関数がありますが、特定の重複がある場合、それが許可されないという問題がありますが、重複が発生する側面とそうでない側面がいくつかあります...

例を挙げて説明します:

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

このデータのリストは、次のように変換されます。

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

今、次のような新しいデータを挿入しようとしています:

    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"]}};

ループの重複チェックを実装する方法を知っている人はいますか?

4

1 に答える 1

1
// 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: 最後の行はただの楽しみです。

于 2012-04-24T17:10:42.327 に答える