[質問の元の表現に関連して注意してください:実際には質問に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はこちら。(結果を表示するには、ブラウザコンソールを開く必要があります。)