javascript - 比较多个对象的多个属性
问题描述
解决方案
我更改了属性以显示一个好的用例。另外,考虑对象的名称或身份(这里我使用了 id 属性)。
var viewport = { width: 2000, height: 1000, ratio: 3 };
var obj1 = { id: '#1', width: 1920, height: 1080, ratio: 1.7 };
var obj2 = { id: '#2', width: 1280, height: 720, ratio: 3 };
var obj3 = { id: '#3', width: 2000, height: 1000, ratio: 1 };
function customSortByProperties(baseViewport, otherViewports) {
let matches = {};
otherViewports.forEach((obj) => {
matches[obj.id] = 0;
for (let property in obj) {
if (baseViewport[property] === obj[property]) {
if (property === 'ratio') {
matches[obj.id] += 2;
} else {
matches[obj.id] += 1;
}
}
}
});
return Object.keys(matches).sort((a, b) => { return matches[b] - matches[a] });
}
console.log(customSortByProperties(viewport, [obj1, obj2, obj3]));
您需要一个数组而不是单个结果,因为可能有两个项目具有相同的匹配计数。