试图通过在onchange事件期间传递参数来筛选对象时,结果得到一个空数组。
在尝试对这些键和值进行硬编码时,它返回一个对象及其工作正常,在这种情况下,它将始终返回一个以Ram为值的数组
var empDetails = [{
name: "Raju",
id: 123
},
{
name: "Ram",
id: 456
}, {
name: "Anand",
id: 789
}, {
name: "Venkat",
id: 987
}
];
function onFilter(columnName) {
var columnValue = document.getElementById(columnName).value;
empDetails = _.filter(empDetails, {
"name": "Ram"
});
console.log(empDetails);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>
<input class="form-control input-sm" id="name" type="text" onchange="onFilter('name')">
但是在下面的例子中,它返回一个空数组
var empDetails = [{
name: "Raju",
id: 123
},
{
name: "Ram",
id: 456
}, {
name: "Anand",
id: 789
}, {
name: "Venkat",
id: 987
}
];
function onFilter(columnName) {
console.log(columnName);
var columnValue = document.getElementById(columnName).value;
console.log(columnValue);
empDetails = _.filter(empDetails, {
columnName: columnValue
});
console.log(empDetails);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>
<input class="form-control input-sm" id="name" type="text" onchange="onFilter('name')">
最佳答案
按预期筛选键"columnName"
而不是"name"
。
此解决方案对您有效,但没有下划线.js
var empDetails = [{
name: "Raju",
id: 123
}, {
name: "Ram",
id: 456
}, {
name: "Anand",
id: 789
}, {
name: "Venkat",
id: 987
}
];
function onFilter(columnName) {
console.log(columnName);
var columnValue = document.getElementById(columnName).value;
console.log(columnValue);
var filteredEmpDetails = empDetails.filter(function (el) {
return el[columnName] === columnValue;
});
console.log(filteredEmpDetails);
}
<input class="form-control input-sm" id="name" type="text" onchange="onFilter('name')">
您可能应该使用内部变量
filteredEmpDetails
才能多次使用onFilter
-函数。关于javascript - Onchange事件期间的UnderScore动态过滤器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47609242/