我一直在過濾來自 json 物件的一系列值。
以下是范圍資料
const contractAmountRange = [
{ id: '1', min: 0, max: 100000, description: 'Less than $100,000' },
{
id: '2',
min: 100001,
max: 500000,
description: '$100,001 to $500,000',
},
{
id: '3',
min: 500000,
max: 1000000,
description: '$500,000 to $1,000,000',
},
{
id: '4',
min: 1000001,
max: 5000000,
description: '$1,000,001 to $5,000,000',
},
{
id: '5',
min: 5000000,
description: 'More than $5,000,000',
},
];
如果選擇了任何一個范圍,我需要使用所選范圍過濾 json 物件。json物件的結構如下:
const data = [
{
tenderNo: 'ASHQ17HH26334',
awardedAmt: 400000,
yearAwarded: 2015,
},
{
tenderNo: 'BFG8765TT14000008',
awardedAmt: 300000,
yearAwarded: 2015,
},
{
tenderNo: 'AFSH00ETT14000009',
awardedAmt: 76071.21,
yearAwarded: 2015,
},
];
這就是我現在所處的位置。
資料是 json 物件
contractAmountRange 是可用范圍的陣列
rangeSelected 是選擇的范圍,由它的 id 表示
const filterData = (data,contractAmountRange,rangeSelected) => {
// let maxRange, minRange;
const rangeMap = {};
for (const item of contractAmountRange) {
rangeMap[item.id] = item;
}
const filteredData = data.filter((el) => {
return (
?????
);
uj5u.com熱心網友回復:
首先find選擇范圍,然后過濾awardedAmt包含在 foundmin和之間的元素max:
const contractAmountRange = [{
id: "1",
min: 0,
max: 100000,
description: "Less than $100,000"
},
{
id: "2",
min: 100001,
max: 500000,
description: "$100,001 to $500,000",
},
{
id: "3",
min: 500000,
max: 1000000,
description: "$500,000 to $1,000,000",
},
{
id: "4",
min: 1000001,
max: 5000000,
description: "$1,000,001 to $5,000,000",
},
{
id: "5",
min: 5000000,
description: "More than $5,000,000",
},
];
const data = [{
tenderNo: "ASHQ17HH26334",
awardedAmt: 400000,
yearAwarded: 2015,
},
{
tenderNo: "BFG8765TT14000008",
awardedAmt: 300000,
yearAwarded: 2015,
},
{
tenderNo: "AFSH00ETT14000009",
awardedAmt: 76071.21,
yearAwarded: 2015,
},
];
const filterData = (data, contractAmountRange, rangeSelected) => {
const foundRange = contractAmountRange.find((x) => x.id === rangeSelected);
if (!foundRange) {
throw new Error("No range found!");
}
const {
min,
max
} = foundRange;
return data.filter(
({
awardedAmt
}) => awardedAmt >= min && awardedAmt <= max
);
};
const output = filterData(data, contractAmountRange, "2");
console.log(output);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/459207.html
標籤:javascript 筛选
