比较 2 个对象数组是否匹配,无论它在 Lodash 中的索引如何?



我有这个对象数组,我想比较:

const arr1 = [{a:'first', b:'second'}, {c:'third', d: 'fourth'}, {e:'fifth', f: 'sixth'}];
const arr2 = [{c:'third', d: 'fourth'},  {e:'fifth', f: 'sixth'}, {a:'first', b:'second'}];

如您所见,类似对象的索引不匹配。我想检查一个数组中的每个对象是否与另一个数组中的对象匹配。

如何在洛达什中实现这一目标?我正在考虑在 js 中使用地图和排序,但我认为这不是一个好主意。

const arr1 = [{a:'first', b:'second'}, {e:'fifth', f: 'sixth'}, {c:'third', d: 'fourth'}];
const arr2 = [{c:'third', d: 'fourth'},  {e:'fifth', f: 'sixth'}, {a:'first', b:'second'}];
let match = JSON.stringify(arr1.sort((x, y) => {
return Object.keys(x)[0] > Object.keys(y)[0]})) 
=== 
JSON.stringify(arr2.sort((x, y) => {
return Object.keys(x)[0] > Object.keys(y)[0]}))
console.log(match)

或者,我们可以根据对象的键进行排序。首先对它们进行排序,排序后,我们可以使用JSON.stringify转换两者并进行比较。

可以只比较每个项目stringifyed,这样它只是一个every后跟.includes,不需要库:

const arrsMatch = (arr1, arr2) => {
const arr2Strings = arr2.map(JSON.stringify);
return arr1.every(item => arr2Strings.includes(JSON.stringify(item)));
};
console.log(arrsMatch(
[{a:'first', b:'second'}, {c:'third', d: 'fourth'}, {e:'fifth', f: 'sixth'}],
[{c:'third', d: 'fourth'},  {e:'fifth', f: 'sixth'}, {a:'first', b:'second'}],
));
console.log(arrsMatch(
[{a:'DOESNT-MATCH', b:'second'}, {c:'third', d: 'fourth'}, {e:'fifth', f: 'sixth'}],
[{c:'third', d: 'fourth'},  {e:'fifth', f: 'sixth'}, {a:'first', b:'second'}],
));

最新更新