我有一种非常天真的方式来比较两个对象属性的子集。当子集中有许多属性时,很难读取。可能有什么替代方案?
const obj1 = {a: 22, b: 33, c: 44};
const obj2 = {a: 22, b: 34, c: 44};
JSON.stringify([obj1.a, obj1.b]) === JSON.stringify([obj2.a, obj2.b])
答案 0 :(得分:3)
子集比较:SubsetCompare
函数对两个对象的子集进行平面比较。
let obj1 = {a: 22, b: 34, c: 44};
let obj2 = {a: 22, b: 34, c: 10};
let subsetCompare = (obj1, obj2, keys) => keys.every(key => obj1[key] === obj2[key]);
console.log(subsetCompare(obj1, obj2, ['a', 'b']));
console.log(subsetCompare(obj1, obj2, ['a', 'b', 'c']))

平面比较:
flatCompare
函数仅比较基本类型成员的值和引用类型成员的引用。
let x = { a : 10};
let y = { a : 10};
let obj1 = {a: 22, b: 34, c: 44, d:y};
let obj2 = {a: 22, b: 34, c: 44, d:x};
let flatCompare = (obj1, obj2) => {
let keys = [];
if((keys = getKeys(obj1)).length != getKeys(obj2).length)
return false;
return keys.every(key => obj1[key] === obj2[key]);
}
let isObject = (obj) => obj === Object(obj);
let getKeys = (obj) => Object.getOwnPropertyNames(obj);
console.log(flatCompare(obj1, obj2));

深度比较:deepCompare
函数递归地比较嵌套对象的基本类型成员的值。
let x = { a : 10};
let y = { a : 10};
let obj1 = {a: 22, b: 34, c: 44, d:y};
let obj2 = {a: 22, b: 34, c: 44, d:x};
let deepCompare = (obj1, obj2) => {
let keys = [];
if((keys = getKeys(obj1)).length != getKeys(obj2).length)
return false;
return keys.every(key => {
if(isObject(obj1[key]) && isObject(obj2[key]))
return deepCompare(obj1[key], obj2[key]);
return obj1[key] === obj2[key];
});
};
let isObject = (obj) => obj === Object(obj);
let getKeys = (obj) => Object.getOwnPropertyNames(obj);
console.log(deepCompare(obj1, obj2))

答案 1 :(得分:1)
为什么不使用功能?
let obj1 = {a: 22, b: 33, c: 44};
let obj2 = {a: 22, b: 34, c: 44};
console.log(compareObjects(obj1, obj2, [`a`, `b`])); // false
console.log(compareObjects(obj1, obj2, [`a`, `c`])); // true
console.log(compareObjects(obj1, obj2, [`b`, `c`])); // false
function compareObjects(obj1, obj2, keys) {
let i;
for (i = keys.length - 1; i > -1 && obj1[keys[i]] === obj2[keys[i]]; i--);
return i === -1; // if i equals -1 it went through the whole loop and did not fail for the second condition
}

答案 2 :(得分:0)
基于@ revilheart的回答,但是@ Ryan的every
建议:
let obj1 = {a: 22, b: 33, c: 44};
let obj2 = {a: 22, b: 34, c: 44};
console.log(compareObjects(obj1, obj2, [`a`, `b`])); // false
console.log(compareObjects(obj1, obj2, [`a`, `c`])); // true
console.log(compareObjects(obj1, obj2, [`b`, `c`])); // false
function compareObjects(obj1, obj2, keys) {
return keys.every(key => obj1[key] === obj2[key])
}