問題是groupByCondition.column
和groupByCondition.value
期待的對象,如groupByCondition = {"column": "col1", "value": "abc"}
但你是在一個不同的方式groupByCondition = {"col1": "abc"}
。
您可以更改groupByCondition
對象,以適應您日後訪問方式:
allRecords = [{"col1": "abc", "col2": "xyz"}, {"col1": "cde", "col2": "zxy"}, {"col1": "1", "col2": "bit"}, {"col1": 1, "col2": "byte"}];
function filterRecords(condition) {
result = allRecords.filter(
function(r){
return r[condition.column] == condition.value;
}
);
console.log('The result of filtering by '+JSON.stringify(condition)+' is');
console.log(result);
return result;
}
result = filterRecords({"column": "col1", "value": "abc"});
result = filterRecords({"column": "col1", "value": "cde"});
result = filterRecords({"column": "col1", "value": "1"});
result = filterRecords({"column": "col1", "value": 1});
或者你可以改變你訪問它,以適應條件對象的方式:
allRecords = [{"col1": "abc", "col2": "xyz"}, {"col1": "cde", "col2": "zxy"}, {"col1": "1", "col2": "bit"}, {"col1": 1, "col2": "byte"}];
function filterRecords(condition) {
key = Object.keys(condition)[0];
result = allRecords.filter(
function(r){
return r[key] == condition[key];
}
);
console.log('The result of filtering by '+JSON.stringify(condition)+' is');
console.log(result);
return result;
}
result = filterRecords({"col1": "abc"});
result = filterRecords({"col1": "cde"});
result = filterRecords({"col1": 1});
result = filterRecords({"col1": "1"});
這兩個示例均假定您基於僅1列/屬性的值篩選記錄。如果您想根據多個條件對其進行過濾,則需要額外的工作。
你能否提供兩個例子,一個是數值,一個是沒有的。我不確定明白你的意思。謝謝。 –
內部過濾器函數'3'和3是不同的,你需要parseInt(val,10) –
或'return r [groupByCondition.column] .toString()== groupByCondition.value.toString();'(它們可能不是整數) – Archer