使用lodash的iSequal()相比,排除某些属性



我正在使用_.isequal比较2个对象数组(例如:每个对象10个属性),并且工作正常。

现在有2个属性(创建和删除),我不必成为比较的一部分。

示例:

var obj1 = {name: "James", age: 17, creation: "13-02-2016", deletion: "13-04-2016"}
var obj2 = {name: "Maria", age: 17, creation: "13-02-2016", deletion: "13-04-2016"}
// lodash method...
_.isEqual(firstArray, secondArray)

您可以使用amit()删除对象中的特定属性。

var result = _.isEqual(
  _.omit(obj1, ['creation', 'deletion']),
  _.omit(obj2, ['creation', 'deletion'])
);

var obj1 = {
  name: "James",
  age: 17,
  creation: "13-02-2016",
  deletion: "13-04-2016"
};
var obj2 = {
  name: "Maria",
  age: 17,
  creation: "13-02-2016",
  deletion: "13-04-2016"
};
var result = _.isEqual(
  _.omit(obj1, ['creation', 'deletion']),
  _.omit(obj2, ['creation', 'deletion'])
);
console.log(result);
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>

@ryeballar的答案对大对象并不好,因为每次进行比较时,都在创建每个对象的深层副本。

最好使用isEqualWith。例如,忽略"创建"one_answers"删除"属性的差异:

var result = _.isEqualWith(obj1, obj2, (value1, value2, key) => {
    return key === "creation" || key === "deletion" ? true : undefined;
});

edit(注释中指出的重要警告):如果对象具有不同数量的键,则isEqualWith认为它们是不同的,无需您的自定义器所做的事情。因此,如果要忽略可选属性,请勿使用此方法。,请考虑使用_.isMatch()_.isMatchWith()或 @Ryeballar的_.omit()方法。

请注意,如果您是为ES5编写的,则必须用函数语法(function() {

替换箭头语法(() => {

_.omit创建对象的深拷贝。如果您只需要排除根本道具,最好创建浅复制使用,例如破坏分配

const x = { a: 4, b: [1, 2], c: 'foo' }
const y = { a: 4, b: [1, 2], c: 'bar' }
const { c: xC, ...xWithoutC } = x
const { c: yC, ...yWithoutC } = y
_.isEqual(xWithoutC, yWithoutC) // true
xWithoutC.b === x.b             // true, would be false if you use _.omit

最佳方式完全不创建副本(typescript):

function deepEqual(
  x?: object | null,
  y?: object | null,
  ignoreRootProps?: Set<string>
) {
  if (x == null || y == null) return x === y
  const keys = Object.keys(x)
  if (!_.isEqual(keys, Object.keys(y)) return false
  for (let key of keys) {
    if (ignoreRootProps && ignoreRootProps.has(key)) continue
    if (!_.isEqual(x[key], y[key])) return false
  }
  return true
}

您可以将数组映射到"已清洁"数组中,然后比较这些数组。

// Create a function, to do some cleaning of the objects.
var clean = function(obj) {
    return {name: obj.name, age: obj.age};
};
// Create two new arrays, which are mapped, 'cleaned' copies of the original arrays.
var array1 = firstArray.map(clean);
var array2 = secondArray.map(clean);
// Compare the new arrays.
_.isEqual(array1, array2);

这有一个缺点,即如果对象期望任何新属性,则需要更新clean函数。可以编辑它,以便将两个不需要的属性删除。

我看到了两个选项。

1)制作不包含创建或日期的每个对象的第二个副本。

2)循环遍历所有属性,并确定它们都具有相同的属性,请尝试这样的东西。

var x ={}
var y ={}
for (var property in x) {
if(property!="creation" || property!="deletion"){
if (x.hasOwnProperty(property)) {
        compare(x[property], y[property])
    }
}
}

其中比较()是一些简单的字符串或对象比较。如果您是一个或两个对象上的属性,则可以进一步简化此代码,但这在大多数情况下都可以使用。

我的最终解决方案需要对可选属性进行完整比较,因此上述解决方案不起作用。

我使用一个浅克隆来删除我想从每个对象中忽略的键,然后与isEqual进行比较:

const equalIgnoring = (newItems, originalItems) => newItems.length === originalItems.length
    && newItems.every((newItem, index) => {
        const rest1 = { ...newItem };
        delete rest1.creation;
        delete rest1.deletion;
        const rest2 = { ...originalItems[index] };
        delete rest2.creation;
        delete rest2.deletion;
        return isEqual(rest1, rest2);
    });

如果要检查数组中的每个项目的子集:

const equalIgnoringExtraKeys = (fullObjs, partialObjs) => 
    fullObjs.length === partialObjs.length
    && fullObjs.every((fullObj, index) => isMatch(fullObj, partialObjs[index]));

如果您也想忽略特定属性并检查子集:

const subsetIgnoringKeys = (fullObjs, partialObjs) => 
    fullObjs.length === partialObjs.length
    && fullObjs.every((fullObj, index) => isMatchWith(
        fullObj,
        partialObjs[index],
        (objValue, srcValue, key, object, source) => {
            if (["creation", "deletion"].includes(key)) {
                return true;
            }
            return undefined;
        }
    ));

最新更新