質問

JavaScript コードでオブジェクトの 2 つの配列を比較したいと考えています。オブジェクトには合計 8 つのプロパティがありますが、各オブジェクトはそれぞれの値を持たず、配列がそれぞれ 8 項目より大きくなることはありません。そのため、それぞれを走査してからプロパティの値を調べるという強引な方法が考えられます。 8 つのプロパティは、私がやりたいことを実現する最も簡単な方法ですが、実装する前に、より洗練されたソリューションを持っている人がいるかどうかを確認したいと思いました。何かご意見は?

役に立ちましたか?

解決

編集:現在の一般的なブラウザベースの JavaScript インタープリターの実装では、演算子をオーバーロードできません。

元の質問に答えるには、次のような方法があります。念のため言っておきますが、これはちょっとしたハックです。 2 つの配列を JSON にシリアル化します。 次に、2 つの JSON 文字列を比較します。これは単に配列が異なるかどうかを示すだけであり、明らかにこれを行うことができます それぞれ 配列内のオブジェクトも調べて、どのオブジェクトが異なっていたかを確認します。

もう 1 つのオプションは、オブジェクトを比較するための優れた機能を備えたライブラリを使用することです。私はこれを使用し、推奨しています。 もちキット.


編集: カメンが出した答え 与えられた 2 つのオブジェクトを比較する 1 つの関数は、私が提案したことを実行するライブラリよりもはるかに小さいため、これも検討に値します (ただし、私の提案は確かに十分に機能します)。

以下に、単純な実装を示します。これで十分に機能します。この実装には潜在的な問題があることに注意してください。

function objectsAreSame(x, y) {
   var objectsAreSame = true;
   for(var propertyName in x) {
      if(x[propertyName] !== y[propertyName]) {
         objectsAreSame = false;
         break;
      }
   }
   return objectsAreSame;
}

両方のオブジェクトがまったく同じプロパティのリストを持っていることが前提です。

ああ、良くも悪くも、私が唯一のリターンポイント派に属していることはおそらく明白です。:)

他のヒント

これは古い質問であることは承知していますが、提供された回答は正常に機能します...ただし、これは少し短く、追加のライブラリは必要ありません(すなわち、JSON ):

function arraysAreEqual(ary1,ary2){
  return (ary1.join('') == ary2.join(''));
}

正直に言うと、オブジェクトごとに最大 8 つのオブジェクトと最大 8 つのプロパティがある場合、各オブジェクトを走査して直接比較するのが最善の策です。早くて簡単になりますよ。

このような種類の比較を頻繁に使用する場合は、JSON シリアル化については Jason の意見に同意します...しかし、そうでない場合は、新しいライブラリや JSON シリアル化コードを使用してアプリの速度を低下させる必要はありません。

2 つのオブジェクトの内容を比較し、相違点のわかりやすいリストを返すための単純なアルゴリズムに少し取り組んでみました。シェアしようと思いました。jQuery のいくつかのアイデアを借用しています。 map 関数の実装とオブジェクトと配列の型チェック。

これは、差分情報を含む配列である「差分オブジェクト」のリストを返します。とてもシンプルです。

ここにあります:

// compare contents of two objects and return a list of differences
// returns an array where each element is also an array in the form:
// [accessor, diffType, leftValue, rightValue ]
//
// diffType is one of the following:
//   value: when primitive values at that index are different
//   undefined: when values in that index exist in one object but don't in 
//              another; one of the values is always undefined
//   null: when a value in that index is null or undefined; values are
//         expressed as boolean values, indicated wheter they were nulls
//   type: when values in that index are of different types; values are 
//         expressed as types
//   length: when arrays in that index are of different length; values are
//           the lengths of the arrays
//

function DiffObjects(o1, o2) {
    // choose a map() impl.
    // you may use $.map from jQuery if you wish
    var map = Array.prototype.map?
        function(a) { return Array.prototype.map.apply(a, Array.prototype.slice.call(arguments, 1)); } :
        function(a, f) { 
            var ret = new Array(a.length), value;
            for ( var i = 0, length = a.length; i < length; i++ ) 
                ret[i] = f(a[i], i);
            return ret.concat();
        };

    // shorthand for push impl.
    var push = Array.prototype.push;

    // check for null/undefined values
    if ((o1 == null) || (o2 == null)) {
        if (o1 != o2)
            return [["", "null", o1!=null, o2!=null]];

        return undefined; // both null
    }
    // compare types
    if ((o1.constructor != o2.constructor) ||
        (typeof o1 != typeof o2)) {
        return [["", "type", Object.prototype.toString.call(o1), Object.prototype.toString.call(o2) ]]; // different type

    }

    // compare arrays
    if (Object.prototype.toString.call(o1) == "[object Array]") {
        if (o1.length != o2.length) { 
            return [["", "length", o1.length, o2.length]]; // different length
        }
        var diff =[];
        for (var i=0; i<o1.length; i++) {
            // per element nested diff
            var innerDiff = DiffObjects(o1[i], o2[i]);
            if (innerDiff) { // o1[i] != o2[i]
                // merge diff array into parent's while including parent object name ([i])
                push.apply(diff, map(innerDiff, function(o, j) { o[0]="[" + i + "]" + o[0]; return o; }));
            }
        }
        // if any differences were found, return them
        if (diff.length)
            return diff;
        // return nothing if arrays equal
        return undefined;
    }

    // compare object trees
    if (Object.prototype.toString.call(o1) == "[object Object]") {
        var diff =[];
        // check all props in o1
        for (var prop in o1) {
            // the double check in o1 is because in V8 objects remember keys set to undefined 
            if ((typeof o2[prop] == "undefined") && (typeof o1[prop] != "undefined")) {
                // prop exists in o1 but not in o2
                diff.push(["[" + prop + "]", "undefined", o1[prop], undefined]); // prop exists in o1 but not in o2

            }
            else {
                // per element nested diff
                var innerDiff = DiffObjects(o1[prop], o2[prop]);
                if (innerDiff) { // o1[prop] != o2[prop]
                    // merge diff array into parent's while including parent object name ([prop])
                    push.apply(diff, map(innerDiff, function(o, j) { o[0]="[" + prop + "]" + o[0]; return o; }));
                }

            }
        }
        for (var prop in o2) {
            // the double check in o2 is because in V8 objects remember keys set to undefined 
            if ((typeof o1[prop] == "undefined") && (typeof o2[prop] != "undefined")) {
                // prop exists in o2 but not in o1
                diff.push(["[" + prop + "]", "undefined", undefined, o2[prop]]); // prop exists in o2 but not in o1

            }
        }
        // if any differences were found, return them
        if (diff.length)
            return diff;
        // return nothing if objects equal
        return undefined;
    }
    // if same type and not null or objects or arrays
    // perform primitive value comparison
    if (o1 != o2)
        return [["", "value", o1, o2]];

    // return nothing if values are equal
    return undefined;
}

私は試した JSON.stringify() そして私のために働いてくれました。

let array1 = [1,2,{value:'alpha'}] , array2 = [{value:'alpha'},'music',3,4];

JSON.stringify(array1) // "[1,2,{"value":"alpha"}]"

JSON.stringify(array2) // "[{"value":"alpha"},"music",3,4]"

JSON.stringify(array1) === JSON.stringify(array2); // false

通常、シリアル化は機能しません(プロパティの順序が一致する場合にのみ機能します)。 JSON.stringify({a:1,b:2}) !== JSON.stringify({b:2,a:1})) プロパティの数を確認し、各プロパティも比較する必要があります。

const objectsEqual = (o1, o2) =>
    Object.keys(o1).length === Object.keys(o2).length 
        && Object.keys(o1).every(p => o1[p] === o2[p]);

const obj1 = { name: 'John', age: 33};
const obj2 = { age: 33, name: 'John' };
const obj3 = { name: 'John', age: 45 };
        
console.log(objectsEqual(obj1, obj2)); // true
console.log(objectsEqual(obj1, obj3)); // false

詳細な比較が必要な場合は、関数を再帰的に呼び出すことができます。

const obj1 = { name: 'John', age: 33, info: { married: true, hobbies: ['sport', 'art'] } };
const obj2 = { age: 33, name: 'John', info: { hobbies: ['sport', 'art'], married: true } };
const obj3 = { name: 'John', age: 33 };

const objectsEqual = (o1, o2) => 
    typeof o1 === 'object' && Object.keys(o1).length > 0 
        ? Object.keys(o1).length === Object.keys(o2).length 
            && Object.keys(o1).every(p => objectsEqual(o1[p], o2[p]))
        : o1 === o2;
        
console.log(objectsEqual(obj1, obj2)); // true
console.log(objectsEqual(obj1, obj3)); // false

この関数を使用すると、配列内のオブジェクトを比較するのが簡単になります。

const arr1 = [obj1, obj1];
const arr2 = [obj1, obj2];
const arr3 = [obj1, obj3];

const arraysEqual = (a1, a2) => 
   a1.length === a2.length && a1.every((o, idx) => objectsEqual(o, a2[idx]));

console.log(arraysEqual(arr1, arr2)); // true
console.log(arraysEqual(arr1, arr3)); // false

これをお試し下さい:

function used_to_compare_two_arrays(a, b)
{
  // This block will make the array of indexed that array b contains a elements
  var c = a.filter(function(value, index, obj) {
    return b.indexOf(value) > -1;
  });

  // This is used for making comparison that both have same length if no condition go wrong 
  if (c.length !== a.length) {
    return 0;
  } else{
    return 1;
  }
}

これが私の試みです。 ノードのアサートモジュール +npmパッケージ オブジェクトハッシュ.

2 つの配列間でオブジェクトの順序が異なる場合でも、2 つの配列に同じオブジェクトが含まれているかどうかを確認したいとします。

var assert = require('assert');
var hash = require('object-hash');

var obj1 = {a: 1, b: 2, c: 333},
    obj2 = {b: 2, a: 1, c: 444},
    obj3 = {b: "AAA", c: 555},
    obj4 = {c: 555, b: "AAA"};

var array1 = [obj1, obj2, obj3, obj4];
var array2 = [obj3, obj2, obj4, obj1]; // [obj3, obj3, obj2, obj1] should work as well

// calling assert.deepEquals(array1, array2) at this point FAILS (throws an AssertionError)
// even if array1 and array2 contain the same objects in different order,
// because array1[0].c !== array2[0].c

// sort objects in arrays by their hashes, so that if the arrays are identical,
// their objects can be compared in the same order, one by one
var array1 = sortArrayOnHash(array1);
var array2 = sortArrayOnHash(array2);

// then, this should output "PASS"
try {
    assert.deepEqual(array1, array2);
    console.log("PASS");
} catch (e) {
    console.log("FAIL");
    console.log(e);
}

// You could define as well something like Array.prototype.sortOnHash()...
function sortArrayOnHash(array) {
    return array.sort(function(a, b) {
        return hash(a) > hash(b);
    });
}

objectsAreSame @JasonBuntingの回答で言及されている関数は、私にとってはうまく機能します。ただし、少し問題があります。もし x[propertyName] そして y[propertyName] オブジェクトです (typeof x[propertyName] == 'object')、それらを比較するには、関数を再帰的に呼び出す必要があります。

を使用して _.some ロダッシュより: https://lodash.com/docs/4.17.11#some

const array1AndArray2NotEqual = 
          _.some(array1, (a1, idx) => a1.key1 !== array2[idx].key1 
                                     || a1.key2 !== array2[idx].key2 
                                     || a1.key3 !== array2[idx].key3);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top