所以我有以下資料集
const data = [
{
id: '11se23-213',
name: 'Data1',
points: [
{ x: 5, y: 1.1 },
{ x: 6, y: 2.1 },
{ x: 7, y: 3.1 },
{ x: 8, y: 1.5 },
{ x: 9, y: 2.9 },
{ x: 10, y: 1.1 }
]
},
{
id: 'fdsf-213',
name: 'Data2',
points: [
{ x: 5, y: 3.1 },
{ x: 6, y: 4.1 },
{ x: 7, y: 2.1 },
{ x: 8, y: 0.5 },
{ x: 9, y: 1.9 },
{ x: 10, y: 1.4 }
]
},
]
在這個資料集上,我正在渲染圖表。我正在嘗試使用資料集實作以下目標。
- 使用最小值和最大值過濾點(用戶在輸入欄位中給出)
- 用戶可以選擇只給出最小值
- 用戶可以選擇只給出最大值
- 用戶可以同時給出最小值和最大值
- 如果用戶洗掉/清除最小值和最大值/輸入,則恢復為原始資料
查看上述要求,最大值和最小值可能為空。
由于我在 Angular 中作業,所以我將粘貼我到目前為止所做的代碼,并在下面寫下我面臨的問題。
組件.ts
const clonedData = data; // Keeping a clone so that I can revert later
const mainData = data; // This is the data I am using for rendering chart and filtering
// Using reactive forms of angular
this.form.valueChanges.pipe(
debounceTime(500),
distinctUntilChanged(),
tap(values => {
if (values.min || values.max) {
this.mainData = this.mainData.map(item => {
return {
...item,
points: items.points.filter(point => point.y >= values.min && point.y <= values.max)
});
return;
}
// If both null revert to original data;
this.mainData = this.clonedData;
}).subscribe()
我了解我的代碼中存在一些問題。
主要問題之一是即使我同時提供最小值和最大值或其中之一,點陣列始終回傳空。
當我清除或洗掉這兩個值時,它會進入 else 條件并恢復為默認資料(正在作業)。
uj5u.com熱心網友回復:
嘗試這個:
const data = [
{
id: '11se23-213',
name: 'Data1',
points: [ { x: 5, y: 1.1 }, { x: 6, y: 2.1 }, { x: 7, y: 3.1 }, { x: 8, y: 1.5 }, { x: 9, y: 2.9 }, { x: 10, y: 1.1 } ]
},
{
id: 'fdsf-213',
name: 'Data2',
points: [ { x: 5, y: 3.1 }, { x: 6, y: 4.1 }, { x: 7, y: 2.1 }, { x: 8, y: 0.5 }, { x: 9, y: 1.9 }, { x: 10, y: 1.4 } ]
}
];
const filter = (arr, min, max) =>
arr.map(e => ({
...e,
points: e.points.filter(({ y }) => (min === null || y >= min) && (max === null || y <= max))
}));
console.log('min=1, max=2', filter(data, 1, 2));
console.log('min=null, max=2', filter(data, null, 2));
console.log('min=1, max=null', filter(data, 1, null));
console.log('min=null, max=null', filter(data, null, null));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/433923.html
標籤:javascript 数组 有角度的 打字稿
