通過匹配值從我的嵌套物件陣列中洗掉資料。就我而言,我想去掉不活動的物件。所以每個包含活動 0 的物件都需要被洗掉。
[
{
"id" : 1,
"title" : 'list of...',
"goals": [
{
"id": 1569,
"active": 0
},
{
"id": 1570,
"active": 1
},
{
"id": 1571,
"active": 0
}
],
},
{
"id" : 2,
"title" : 'more goals',
"goals": [
{
"id": 1069,
"active": 0
},
{
"id": 1070,
"active": 1
},
],
},
]
以下將以未更改的狀態回傳陣列
public stripGoalsByInactiveGoals(clusters) {
return clusters.filter(cluster =>
cluster.goals.filter(goal => goal.active === 1)
);
}
uj5u.com熱心網友回復:
array.filter 等待一個布林值以知道它是否必須過濾資料
在您的情況下,您有一個陣列陣列,您想按活動目標過濾“子”陣列
如果您只想保留活動目標,請按地圖更改您的第一個過濾器以回傳按條件過濾的陣列的修改值
function stripGoalsByInactiveGoals(clusters) {
return clusters.map(cluster => {
return {
goals: cluster.goals.filter(goal => goal.active)
};
});
}
var data = [{
"goals": [{
"id": 1569,
"active": 0
},
{
"id": 1570,
"active": 1
},
{
"id": 1571,
"active": 0
}
],
},
{
"goals": [{
"id": 1069,
"active": 0
},
{
"id": 1070,
"active": 1
},
],
},
];
function stripGoalsByInactiveGoals(clusters) {
return clusters.map(cluster => {
return {
goals: cluster.goals.filter(goal => goal.active)
};
});
}
console.log(stripGoalsByInactiveGoals(data));
uj5u.com熱心網友回復:
您可以創建另一個陣列(在您需要輸入不變的情況下)并回圈輸入,附加每個成員物件的過濾目標陣列。如果過濾器后的目標為空,您也可以避免附加該專案,但此示例沒有這樣做,因為它沒有被指定為要求。
let input = [
{
"goals": [
{
"id": 1569,
"active": 0
},
{
"id": 1570,
"active": 1
},
{
"id": 1571,
"active": 0
}
],
},
{
"goals": [
{
"id": 1069,
"active": 0
},
{
"id": 1070,
"active": 1
},
],
},
]
let output = [];
for (let item of input) {
output.push({goals: item.goals.filter(element => (element.active))})
}
console.log(output);
uj5u.com熱心網友回復:
您可以按照這個動態方法:
stripGoalsByInactiveGoals(clusters) {
var res = [];
this.data.forEach((item) => {
let itemObj = {};
Object.keys(item).forEach((key) => {
itemObj[key] = item[key].filter(x => x.active != 0);
res.push(itemObj);
});
});
return res;
}
Stackbiltz 演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/490601.html
標籤:javascript
上一篇:如何防止更新v-model輸入?
