0

以下について:

var arr = [{ "packageId": "11", "machineId": "1", "operationType": "Download" }, { "packageId": "12", "machineId": "1", "operationType": "Download" }, { "packageId": "14", "machineId": "1", "operationType": "Download" }];
var index = arr.indexOf({ "packageId": "12", "machineId": "1", "operationType": "Download" });
console.log("index: " + index);
arr.splice(index, 1);

-1結果としていつも得ます。何故ですか?

配列からオブジェクトを削除できるようにする必要があります。

4

3 に答える 3

2

[質問の元の表現に関連して注意してください:実際には質問にJSONはありません。JSONはオブジェクト表記を指します。配列とindexOf()呼び出しの中にあるのはオブジェクトリテラルであり、オプションのプロパティで表され{}ます。]

オブジェクトの比較

問題は、呼び出し内で作成するオブジェクトリテラルindexOf()はそれ自体が新しいオブジェクトであるため、配列内のオブジェクトと等しくarrないことです。代わりに、各オブジェクトのすべてのプロパティをループして、それらの同等性を確認する必要があります。私はこの関数をすぐに作成しました。この回答の下部にあるJSFiddleリンクでテストできます。

function compareObjs(obj1, obj2) {
    var k,
        rtn = true; // assume objects are similar, and then attempts to falsify
    for (k in obj1) {
        if (obj1.hasOwnProperty(k) && obj2.hasOwnProperty(k)) { // check property belongs to both obj1 and obj2
            if (typeof obj1[k] === 'Object') {
                compareObjs(obj1, obj2); // recursive call, to compare two objects within the object
            } else {
                rtn = (obj1[k] === obj2[k]) ? rtn : false; // check value of property is equivalent; if not set the return value to false
            }
        } else {
            rtn = false;
        }
    }
}

2つのオブジェクトをフィードするので、質問では次のようになります。

compareObjs(arr[1], { "packageId": "12", "machineId": "1", "operationType": "Download" });

これはtrueを返すはずです。2つのオブジェクトが同等でない場合は、falseを返します。

配列要素を見つける

これを使用して、配列内の特定のパッケージの位置を確認することをお勧めします。この場合、配列内の各オブジェクトが同等かどうかを確認するために、配列をループする必要があります。

var i = 0, // Declare the variables upfront
    l = arr.length, // including the length of the array
    r = -1;  // and where you want your result, which will automatically be -1 until a match is found.
for (i; i < l; i += 1) {
    r = (compareObjs(arr[i], { "packageId": "12", "machineId": "1", "operationType": "Download" }) && r === -1) ? i : r;
}

rこれにより、同等のオブジェクトが見つかった最初の位置がわかります。

関連する配列要素の削除

次に、次のようなメソッドrを使用して、を参照して配列からオブジェクトを削除できます。splice()

arr.splice(r, 1);

このコードを関数にドロップすることもできますが、プログラムの残りの部分の構造がわからないので、それについて考えてみてください。

JSFiddleはこちら(結果を表示するには、ブラウザコンソールを開く必要があります。)

于 2013-02-28T16:00:54.323 に答える
1

私はあなたに別の可能な解決策を提案します。

データ構造を変更できる場合は、オブジェクトを使用してデータを保存し、連想配列として整形します。

var assocArr = new Object();
assocArr["11"] = {"packageId": "11", "machineId": "1", "operationType": "Download"};
assocArr["12"] = { "packageId": "12", "machineId": "1", "operationType": "Download" };
assocArr["14"] = { "packageId": "14", "machineId": "1", "operationType": "Download" };

delete assocArr["11"];

利点:

  • 直接データアクセス
  • 些細な挿入と削除

データを管理するためのクラスを手配することもできます。

var AssocArray = function(){
  var collection = new Object();

  this.add = function(id, o){
    collection[id] = o;
  }

  this.remove = function(id){
    delete collection[id];
  }

  this.getById = function(id){
    return collection[id];
  }

  this.get = function(){
    return collection;
  }
}

var myAssoc = new AssocArray();
myAssoc.add("11",{"packageId": "11", "machineId": "1", "operationType": "Download"});
myAssoc.add("12",{ "packageId": "12", "machineId": "1", "operationType": "Download"});
myAssoc.add("14",{ "packageId": "14", "machineId": "1", "operationType": "Download"});

if(myAssoc.getById("10")) myAssoc.remove("10");
if(myAssoc.getById("14")) myAssoc.remove("14");

console.log(myAssoc.get());
于 2013-02-28T15:52:57.843 に答える
1

作成しているオブジェクトリテラルは、実際にはの{}オブジェクトとは異なるオブジェクトであるarrため、直接比較することはできず、indexOf失敗します。古き良き時代のイテレーションを使用する必要があります。

arr.filter(function (elem) {
    return elem.packageId != 12
        || elem.machineId != 1
        || elem.operationType != 'Download';
});

もちろん、必要に応じてオブジェクトと比較することもできます。

var compareTo = {'packageId': '12'};
arr.filter(function (elem) {
    var matches = 0, elements = 0;
    for (var x in compareTo) {
        elements++;
        if (compareTo.hasOwnProperty(x) && elem.hasOwnProperty(x)
            && elem (x) == compareTo(x)
        ) {
            matches++;
        }
    }
    return matches == elements;
});
于 2013-02-28T15:12:06.103 に答える