как сравнить 2 массива объектов
Имеются 2 массива объектов, как произвести строгое сравнение
[
{ id: 1, name: 1, text: 'test1' },
{ id: 2, name: 2, text: 'test2' },
{ id: 3, name: 3, text: 'test3' },
{ id: 4, name: 4, text: 'test4' },
{ id: 5, name: 5, text: 'test5' },
],
[
{ id: 1, name: 1, text: 'test1' },
{ id: 2, name: 2, text: 'test2' },
{ id: 3, name: 3, text: 'test3' },
{ id: 4, name: 4, text: 'test4' },
{ id: 5, name: 5, text: 'test5' },
],
Ответы (2 шт):
Автор решения: vsemozhebuty
→ Ссылка
Если нет вложенных структур, все значения примитивны и порядок объектов тоже должен совпадать, можно попробовать так:
const arr1 = [
{ id: 1, name: 1, text: 'test1' },
{ id: 2, name: 2, text: 'test2' },
{ id: 3, name: 3, text: 'test3' },
{ id: 4, name: 4, text: 'test4' },
{ id: 5, name: 5, text: 'test5' },
];
const arr2 = [
{ id: 1, name: 1, text: 'test1' },
{ id: 2, name: 2, text: 'test2' },
{ id: 3, name: 3, text: 'test3' },
{ id: 4, name: 4, text: 'test4' },
{ id: 5, name: 5, text: 'test5' },
];
function isEqual(a1, a2) {
if (a1.length !== a2.length) return false;
for (let i = 0; i < a1.length; i++) {
const obj1 = a1[i];
const obj2 = a2[i];
if (Object.keys(obj1).length !== Object.keys(obj2).length) return false;
for (const [key1, value1] of Object.entries(obj1)) {
if (obj2[key1] !== value1) return false;
}
}
return true;
}
console.log(isEqual(arr1, arr2));
console.log(isEqual(arr1, arr2.concat({})));
arr2[0].text = 'foo';
console.log(isEqual(arr1, arr2));
Автор решения: yar85
→ Ссылка
Для массивов и базовых объектов (не для Date/Set/Map/HTMLElement/итд):
const [arrayOne, arrayTwo] = getTestArrays();
// магия
const compareObj = (a, b) => {
const aKeys = Object.keys(a);
if (aKeys.length !== Object.keys(b).length) return 'различается количество свойств';
let recResult;
for (const key of aKeys) {
if (!b.hasOwnProperty(key)) return 'отсутствует как минимум одно собственное свойство';
if (typeof a[key] === 'object') {
if (!+(recResult = compareObj(a[key], b[key]))) return recResult;
} else {
if (typeof a[key] !== typeof b[key]) return 'различаются типы значений как минимум одного свойства';
if (a[key] !== b[key]) return 'различается как минимум одно значение';
}
}
return true;
};
// тесты
console.log('1.', compareObj(arrayOne, arrayTwo));
arrayOne[3].name = String(arrayOne[3].name);
console.log('2.', compareObj(arrayOne, arrayTwo));
arrayOne[2].text = 'lalala';
console.log('3.', compareObj(arrayOne, arrayTwo));
delete arrayOne[1].text;
console.log('4.', compareObj(arrayOne, arrayTwo));
arrayOne[1].toString = 'omg!';
console.log('5.', compareObj(arrayOne, arrayTwo));
// просто чтобы вниз эти массивы спихнуть
function getTestArrays() {
return [
[
{ id: 1, name: 1, text: 'test1' },
{ id: 2, name: 2, text: 'test2' },
{ id: 3, name: 3, text: 'test3' },
{ id: 4, name: 4, text: 'test4' },
{ id: 5, name: 5, text: 'test5' },
], [
{ id: 1, name: 1, text: 'test1' },
{ id: 2, name: 2, text: 'test2' },
{ id: 3, name: 3, text: 'test3' },
{ id: 4, name: 4, text: 'test4' },
{ id: 5, name: 5, text: 'test5' },
],
];
}