const obj1 = {a: 1, b: 2, c: 3, d: 3};
const obj2 = {a: 1, b: 1, e: 2, f: 2, g: 3, h: 5};
// x or X is key or value or key/value pair
const getXs = (obj, getX) =>
Object.keys(obj).map(key => getX(obj, key));
const getPctSameXs = (getX, filter) =>
(objA, objB) =>
(filter ? filter(getXs(objB, getX)) : getXs(objB, getX)).reduce(
(numSame, x) =>
getXs(objA, getX).indexOf(x) > -1 ? numSame + 1 : numSame,
0
)/Object.keys(objA).length * 100;
const pctSameKeys = getPctSameXs((obj, key) => key);
const pctSameValsDups = getPctSameXs((obj, key) => obj[key]);
const pctSameValsNoDups = getPctSameXs((obj, key) => obj[key], vals => [...new Set(vals)]);
const pctSameProps = getPctSameXs((obj, key) => JSON.stringify({[key]: obj[key]}));
console.log('obj1:', JSON.stringify(obj1));
console.log('obj2:', JSON.stringify(obj2));
console.log('% same keys: ', pctSameKeys (obj1, obj2));
console.log('% same values, incl duplicates:', pctSameValsDups (obj1, obj2));
console.log('% same values, no duplicates: ', pctSameValsNoDups(obj1, obj2));
console.log('% same properties (k/v pairs): ', pctSameProps (obj1, obj2));
匹配鍵或值的百分比? –
你有什麼試過的?它出了什麼問題?人們願意幫助,而不是爲你做。 – jdmdevdotnet