如何检查两个对象的相等性(仅特定键值)

q5lcpyga  于 2021-09-13  发布在  Java
关注(0)|答案(4)|浏览(306)

如何检查两个对象(仅特定键值)的相等性,一个对象类型是数字,另一个是字符串类型,但它们是数字。我想检查两个对象的x1、x2、x3和x4值是否相等,而不是所有的对象值

var object1 = {
        id: 1234
        x1: "1.000000",
        x2: undefined,
        x3: "1.0",
        x4: "1.0",
        x5: somevale 1
};
var object2 = {
        id: 3456
        x1: 1,
        x2: undefined,
        x3: 1,
        x4: 1,
        x5: somevalue 2
};

我从如何检查两个对象的相等性中得到了答案,一个对象的属性类型是数字,另一个对象的类型是字符串,但它们是数字。该解决方案检查对象的每个属性,我对我的两个对象得到的属性为false,因为其他属性不能相同。

h4cxqtbf

h4cxqtbf1#

如果两个对象具有相同的关键点,可以使用 Object.keys .

function keysEqual(obj1, obj2){
    const keys1 = Object.keys(obj1), keys2 = Object.keys(obj2);
    return keys1.length === keys2.length && keys1.every(key => keys2.includes(key))
}
var object1 = {
        id: 1234,
        x1: "1.000000",
        x2: undefined,
        x3: "1.0",
        x4: "1.0",
        x5:  1
};
var object2 = {
        id: 3456,
        x1: 1,
        x2: undefined,
        x3: 1,
        x4: 1,
        x5:  2
};
console.log(keysEqual(object1, object2));
9q78igpj

9q78igpj2#

这是对前面问题的已接受答案的修改版本——如果字段“x1”、“x2”、“x3”、“x4”是宽松相等的,则两个对象只考虑相等。
该算法的要点是使用js every 功能:对于[“x1”、“x2”、“x3”、“x4”]中的每个字段, object1 必须(松散地)相等 object2 在那个领域

const fieldsToCheck = ["x1", "x2", "x3", "x4"];

function equal(obj1, obj2, fieldsToCheckFor = fieldsToCheck) {
  return fieldsToCheckFor.every((key) => obj1[key] == obj2[key]);
}

var object1 = {
  id: 1234,
  x1: "1.000000",
  x2: undefined,
  x3: "1.0",
  x4: "1.0",
};
var object2 = {
  id: 3456,
  x1: 1,
  x2: undefined,
  x3: 1,
  x4: 1,
};

var object3 = {
  id: 3456,
  x1: 1,
  x2: undefined,
  x3: 1,
  x4: 1,
  x5: 7,
  randomFieldThatDoesNotGetChecked: "a72",
};

var object4 = {
  id: 3456,
  x1: 1,
  x2: "x2 has been defined",
  x3: 1,
  x4: 1,
  x5: 7,
  randomFieldThatDoesNotGetChecked: "a72",
};

// Should be True
console.log("Test1", equal(object1, object2));

// Should be True
console.log("Test2", equal(object2, object3));

// Should be False
console.log("Test3", equal(object1, object4));
k4ymrczo

k4ymrczo3#

var object1 = {
        id: 1234,
        x1: "1.000000",
        x2: undefined,
        x3: "1.0",
        x4: "1.0",
        x5: 1
};
var object2 = {
        id: 3456,
        x1: 1,
        x2: undefined,
        x3: 1,
        x4: 1,
        x5: 2
};

var check = ["x1", "x2", "x3", "x4"];

console.log(eval());

function eval() {
  for (var i = 0; i < check.length; i++) {
    if (object1[check[i]] != object2[check[i]]) return false;
  }
  return true;
}
but5z9lq

but5z9lq4#

您可以使用 array#every 并检查两个对象中是否存在键,然后比较它们的值。

const object1 = { id: 1234, x1: "1.000000", x2: undefined, x3: "1.0", x4: "1.0", x5: 'somevale 1' },
      object2 = { id: 3456, x1: 1, x2: undefined, x3: 1, x4: 1, x5: 'somevalue 2' },
      keys = ['x1', 'x2', 'x3', 'x4'],
      result = keys.every(key => key in object1 && key in object2 && object1[key] == object2[key]);
console.log(result);

相关问题