简体   繁体   English

将两个对象与 arrays 进行质量比较

[英]Comparing an two objects with arrays for quality

I am currently building a filter system and I am encountering a problem where I want to prevent double filtering if the order of array elements are changed.我目前正在构建一个过滤系统,我遇到了一个问题,如果数组元素的顺序发生变化,我想防止双重过滤。

For example, I got this object:例如,我得到了这个 object:

const filters = {
  brands: [],
  models: [],
}

User A chooses the brand Audi (id 5f1d5077b261aa63f42cc8a9 ) and BMW (id 5f1d5077b261aa63f42cc8aa ) So you get this object:用户 A 选择品牌 Audi (id 5f1d5077b261aa63f42cc8a9 ) 和 BMW (id 5f1d5077b261aa63f42cc8aa ) 所以你得到这个 object:

{
  brands: ["5f1d5077b261aa63f42cc8a9", "5f1d5077b261aa63f42cc8aa"],
  models: [],
}

User B does the same, but in opposite (so first BMW, then Audi).用户 B 做同样的事情,但相反(首先是宝马,然后是奥迪)。 So we end up with this:所以我们最终得到了这个:

{
  brands: ["5f1d5077b261aa63f42cc8aa", "5f1d5077b261aa63f42cc8a9"],
  models: [],
}

(Notice the difference between the order of brands) (注意品牌顺序的区别)

Now when I check these for equality using Lodash isEqual with this code:现在,当我使用Lodash isEqual和以下代码检查这些是否相等时:

const _ = require("lodash");

const filtersA = {
    brands: ["5f1d5077b261aa63f42cc8a9", "5f1d5077b261aa63f42cc8aa"],
    models: [],
};

const filtersB = {
    brands: ["5f1d5077b261aa63f42cc8aa", "5f1d5077b261aa63f42cc8a9"],
    models: [],
};

console.log(_.isEqual(filtersA, filtersB));

This returns false unfortunately, then I tried comparing only the brands together, like:不幸的是,这返回false ,然后我尝试只比较品牌,例如:

console.log(_.isEqual(filtersA.brands, filtersB.brands);

That also returns false .这也返回false

My goal is to return true if the filters in the object are equal, without looking at the order of the other filter.如果 object 中的过滤器相等,我的目标是返回 true,而不查看其他过滤器的顺序。 As long as the same items exist it should return true只要存在相同的项目,它就应该返回 true

I also read something about Lodash isEqualWith , but I am not really understanding how to use it.我还阅读了一些关于Lodash isEqualWith的内容,但我并不真正了解如何使用它。

I fixed it using the following function, this will only work if the two objects have the same structure.我使用以下 function 修复了它,这仅在两个对象具有相同结构时才有效。

const _ = require("lodash");

const filtersA = {
    brands: ["5f1d5077b261aa63f42cc8a9", "5f1d5077b261aa63f42cc8aa"],
    models: [],
};

const filtersB = {
    brands: ["5f1d5077b261aa63f42cc8aa", "5f1d5077b261aa63f42cc8a9"],
    models: [],
};

/**
 * Checks if two objects with arrays are equal
 *
 * @param {Object} a
 * @param {Object} b
 */
const areObjectWithArraysEqual = (a, b) => Object.keys(a).every((key) => _.isEqual(a[key].sort(), b[key].sort()));

console.log(areObjectWithArraysEqual(filtersA, filtersB));

This returns true as expected这将按预期返回true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM