【问题标题】:how to remove sessionID:null value objects from the array nested inside the array of objects in js如何从嵌套在js对象数组中的数组中删除sessionID:null值对象
【发布时间】:2020-07-04 12:00:21
【问题描述】:
[
    {
        "_id": "5edfb4e587a1873120735dcf",
        "firstname": "abc",
        "lastname": "abc",
        "sessions": [
            {
                "_id": "5efc68d146d8330a449e7108",
                "sessionID": null
            },
            {
                "_id": "5efc68e646d8330a449e710a",
                "sessionID": null
            }
        ]
    },
    {
        "_id": "5eedf5685bdb7d33c83186e7",
        "firstname": "sam",
        "lastname": "ple",
        "sessions": [
            {
                "_id": "5efc692d46d8330a449e710c",
                "sessionID": null
            }
        ]
    },
    {
        "_id": "5ef04df83e41dd5b78fe6908",
        "firstname": "User",
        "lastname": "name1",
        "sessions": [
            {
                "_id": "5efc6a8846d8330a449e710e",
                "sessionID": null
            },
            {
                "_id": "5efc6abd46d8330a449e7110",
                "sessionID": null
            }
        ]
    },
    {
        "_id": "5efe0d0c7300073244d765d9",
        "sessions": [],
        "firstname": "User",
        "lastname": "name1"
    }
]

【问题讨论】:

  • -您需要 mongo 查询/javascript 代码吗? -& 添加你需要的输出。所以我会给出答案
  • 我正在使用 :- Artists = await Artist.find({}).populate({ path:'sessions.sessionID', populate:{ path:'agency', select:'_id firstname lastname ' }, match:filterObj }).select('_id firstname lastname sessions').limit(limit).skip(startIndex) 来获取数据,它正在返回问题中提到的数据....我不;t在填充之后想要空值。

标签: javascript arrays json mongodb object


【解决方案1】:

您需要映射您的数组并过滤掉带有 null 的会话

let originalArray = [
    {
        "_id": "5edfb4e587a1873120735dcf",
        "firstname": "abc",
        "lastname": "abc",
        "sessions": [
            {
                "_id": "5efc68d146d8330a449e7108",
                "sessionID": null
            },
            {
                "_id": "5efc68e646d8330a449e710a",
                "sessionID": null
            }
        ]
    },
    .... the rest of your orignal object
]

let newArray = originalArray.map(item => {
    let sessions = item.sessions.filter(session => {
        return session.sessionID !== null
    })

    return {
        ...item,
        sessions
    }
})

【讨论】:

    猜你喜欢
    • 2022-10-17
    • 2021-12-28
    • 2020-08-02
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-30
    • 1970-01-01
    相关资源
    最近更新 更多