通过键从数组中删除对象

时间:2020-06-22 13:20:59

标签: angular typescript ionic-framework

我有这个数组:

this.menuItems = [
        {
            category: 'category 4',
            items: [
                {
                    type: 'link',
                    icon: '',
                },
                {
                    type: 'link',
                    icon: '',
                },
            ]
        },
        {
            category: 'category 1',
            items: [
                {
                    type: 'text',
                    icon: 'pencil'
                },
                {
                    type: 'checkbox',
                    icon: 'pencil'
                },
            ]
        },

我想从menuItems中删除类型为checkbox的对象。 我这样尝试过:

this.menuItems.forEach(category => {
            category.items.forEach((item, index) => {
                if (item.type === 'checkbox') {
                    category.splice(index, 1);
                }
            });
        });

但是不起作用。你能帮我一些建议吗?提前谢谢

1 个答案:

答案 0 :(得分:5)

  1. map
  2. filter

const menuItems = [
    {
        category: 'category 4',
        items: [
            {
                type: 'link',
                icon: '',
            },
            {
                type: 'link',
                icon: '',
            },
        ],
    },
    {
        category: 'category 1',
        items: [
            {
                type: 'text',
                icon: 'pencil',
            },
            {
                type: 'checkbox',
                icon: 'pencil',
            },
        ],
    },
];

const result = menuItems.map(item => ({ ...item, items: item.items.filter(i => i.type !== 'checkbox') }));

console.log(result);