我正在尝试过滤表单对象并匹配一个' Package'对象并返回最匹配对象的数组名称。
var personA = {
name: "Budi",
age: 35,
occupation: "Engineer",
noRooms: 5,
minIncome: 35000,
maxIncome: 60000,
minBudgetPMth: 450,
maxBudgetPMth: 450,
minSqft: 900,
maxSqft: 900
}
从对象键中找到此数组的匹配。
var affordableHDB = [
{
name: "5-room",
minSqft: 860,
maxSqft: 1100,
noRooms: 5,
minIncome: 45000,
maxIncome: 10000,
minBudgetPMth: 400,
maxBudgetPMth: 700
},
{
name: "4-room",
minSqft: 430,
maxSqft: 910,
noRooms: 4,
minIncome: 30000,
maxIncome: 75000,
minBudgetPMth: 400,
maxBudgetPMth: 700
},
{
name: "3-room",
minSqft: 320,
maxSqft: 710,
noRooms: 3,
minIncome: 18000,
maxIncome: 42000,
minBudgetPMth: 200,
maxBudgetPMth: 450
},
{
name: "2-room",
minSqft: 270,
maxSqft: 330,
noRooms: 2,
minIncome: 15000,
maxIncome: 28000,
minBudgetPMth: 150,
maxBudgetPMth: 260
}
];
一个函数应该接受表单数据(person对象)和这个数组(affordableHDB)并返回前两个最匹配的数组名称。例如。 ' Room-5',' Room-4'。非常感谢!
答案 0 :(得分:0)
您可以使用constaints和评级方案,例如计算所有约束,谁是真的并将其用作分数。稍后对结果进行排序并采取最重要的计数。
var person = { name: "Budi", age: 35, occupation: "Engineer", noRooms: 5, minIncome: 35000, maxIncome: 60000, minBudgetPMth: 450, maxBudgetPMth: 450, minSqft: 900, maxSqft: 900 },
affordableHDB = [{ name: "5-room", minSqft: 860, maxSqft: 1100, noRooms: 5, minIncome: 45000, maxIncome: 10000, minBudgetPMth: 400, maxBudgetPMth: 700 }, { name: "4-room", minSqft: 430, maxSqft: 910, noRooms: 4, minIncome: 30000, maxIncome: 75000, minBudgetPMth: 400, maxBudgetPMth: 700 }, { name: "3-room", minSqft: 320, maxSqft: 710, noRooms: 3, minIncome: 18000, maxIncome: 42000, minBudgetPMth: 200, maxBudgetPMth: 450 }, { name: "2-room", minSqft: 270, maxSqft: 330, noRooms: 2, minIncome: 15000, maxIncome: 28000, minBudgetPMth: 150, maxBudgetPMth: 260 }],
scores = affordableHDB.map(function (a) {
var score = 0,
constraints = [
{ keys: ['noRooms'], fn: function (p, f) { return p === f; } },
{ keys: ['minSqft', 'minIncome', 'minBudgetPMth'], fn: function (p, f) { return p >= f; } },
{ keys: ['maxSqft', 'maxIncome', 'maxBudgetPMth'], fn: function (p, f) { return p <= f; } }
];
constraints.forEach(function (c) {
c.keys.forEach(function (k) {
score += c.fn(person[k], a[k]);
});
});
return { score: score, name: a.name };
});
scores.sort(function (a, b) { return b.score - a.score; });
console.log(scores.slice(0, 2).map(function (a) { return a.name; }));
console.log(scores);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;