繁体   English   中英

通过匹配值从我的嵌套对象数组中删除数据

[英]Remove data from my nested array of objects by matching values

通过匹配值从我的嵌套对象数组中删除数据。 就我而言,我想去掉不活动的对象。 所以每个包含活动 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)
    );
}

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));

您可以创建另一个数组(在您需要输入不变的情况下)并循环输入,附加每个成员对象的过滤目标数组。 如果过滤器后的目标为空,您也可以避免附加该项目,但此示例没有这样做,因为它没有被指定为要求。

 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);

您可以按照这个动态方法:

 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 演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM