【问题标题】:filter nested array of object javascript过滤对象javascript的嵌套数组
【发布时间】:2021-07-14 03:46:53
【问题描述】:

我要过滤 hasPermission 状态为 false 以移除该对象:

这是我的对象数组:

const videos = [
    {
        name: ' name',
        url: '1',
        hasPermission: true,
        tags: [
            {
                tag: 'reels',
                hasPermission: true
            },
            {
                tag: 'reels2',
                hasPermission: false
            }
        ]
    },
    {
        name: ' name2',
        url: '2',
        hasPermission: false,
        tags: [
            {
                tag: 'demos',
                hasPermission: true
            },
            {
                tag: 'demos',
                hasPermission: true
            }
        ]
    },
    {
        name: 'video name3',
        url: '2',
        hasPermission: false
    }
];

预期的输出是:

{
        name: ' name',
        url: '1',
        hasPermission: true,
        tags: [
            {
                tag: 'reels',
                hasPermission: true
            }
        ]
    }

首先我想检查主对象 hasPermission 状态是否为 false 删除该对象。如果主对象 hasPermission 状态为真,则检查标签的子对象如果标签对象 hasPermission 为假,则仅删除这些对象。

【问题讨论】:

标签: javascript filter


【解决方案1】:

使用过滤器和地图。

首先我们过滤掉主要对象: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

然后我们映射结果并使用另一个过滤器和对象解构来修改标签。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

const filtered_videos = videos.filter(item => item.hasPermission).map(item => {
    return {
        ...item,
        tags: item.tags ? item.tags.filter(tag => tag.hasPermission) : [],
    }
})

【讨论】:

    猜你喜欢
    • 2019-10-15
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-11
    • 2020-03-08
    相关资源
    最近更新 更多