我的布局中有三个按钮,使用户可以根据所选年份对内容进行过滤。这些按钮如下所示
2019 2018 2017 or berfore
主数据是一个看起来像
的对象的数组const data = [
{
.....
year: "2018"
},
{
.....
year: "2017"
},
{
.....
year: "2016"
},
{
.....
year: "2019"
},
{
.....
year: "2015"
},
]
我能够过滤 2019 和 2018 按钮的内容。但是,当用户选择 2017或更早版本时,它需要过滤2017年及之前任何一年的内容。
此刻我的代码
data.filter(val => val.year === pickedYear) //filter data by year
.map(...) // do more based on filtered data
关于如何处理 2017年或更早版本用例的任何建议?
答案 0 :(得分:1)
尝试这样的事情:
const pickedYear = "2017";
const data = [
{
year: "2018"
},
{
year: "2017"
},
{
year: "2016"
},
{
year: "2019"
},
{
year: "2015"
}
];
const filteredData = data.filter((data) => {
return parseInt(pickedYear) > 2017 ? data.year === pickedYear : parseInt(data.year) <= 2017;
});
console.log(JSON.stringify(filteredData));
答案 1 :(得分:1)
我们可以利用强制类型:
const data = [
{
year: "2018"
},
{
year: "2017"
},
{
year: "2016"
},
{
year: "2019"
},
{
year: "2015"
}
];
const filterByYear = yearFilter => data.filter(({year}) => yearFilter > 2017 ? year == yearFilter : year < 2018);
console.log(filterByYear('2019'));
console.log(filterByYear('2018'));
console.log(filterByYear('2017 or before'))
答案 2 :(得分:0)
根据当前年份,这是一个更强大的示例。值得注意的是,它包括该语言的更新/较少使用的机制,包括:
eval
的有效示例-尽管确实不必要尽管浏览器的兼容性会有所不同,但它也不使用jQuery。这不是一个完整的解决方案,但旨在帮助证明可能发生的事情的可能性:
const buttons = document.querySelectorAll('.btn.filter')
const buttonDetails = buttonGen(buttons.length) // use generator for dynamic button
// Create Buttons (text, event, value, etc)
buttons.forEach(el => {
let data = buttonDetails.next().value
el.value = data.value
el.textContent = data.text
// set button text based on 'value'
el.addEventListener('click', filterData) // add click handler
})
// Button Click function
function filterData() {
let button = this;
let btn_year, op;
if (isNaN(button.textContent)) {
btn_year = button.value
op = '<='
} else {
btn_year = button.value
op = '=='
}
let data = fetchData()
filtered_data = data.filter(data => eval(`${data.year} ${op} ${btn_year}`))
console.log(JSON.stringify(filtered_data));
return filtered_data
}
// Some function will most likely be an AJAX-fetch
function fetchData() {
return [{
year: "2018"
},
{
year: "2017"
},
{
year: "2016"
},
{
year: "2019"
},
{
year: "2015"
}
]
}
// Button Info Generator
function* buttonGen(button_count) {
const current_year = (new Date).getFullYear();
let year = current_year
while (true) {
if (year <= current_year - button_count + 1)
yield {
text: 'earlier',
value: year
}
else
yield {
text: year,
value: year
}
year--
}
}
button {
text-transform: capitalize
}
<button class="btn filter"></button>
<button class="btn filter"></button>
<button class="btn filter"></button>