繁体   English   中英

Javascript 满足条件时更新数组,否则将新记录添加到数组中

[英]Javascript update array when condition is met otherwise add new record to the array

我有一个数组userRoleArray ,例如:

[
    {
        userId: 1,
        userRoles: [
            { userRoleId: 1, roleName: "A" },
            { userRoleId: 2, roleName: "B" }
        ]
    },
    {
        userId: 2,
        userRoles: [
            { userRoleId: 2, roleName: "B" },
            { userRoleId: 3, roleName: "C" }
        ]
    }
]

我要做的是给定目标userId和 new userRoles ,如果我能找到userId ,我将添加新的userRoles ,否则,如果找不到userId ,我会将新记录添加到数组中。

这是我尝试过的:

const findStatus = userRoleArray.find((item) => {
    return item.userId === userId
})
if (!findStatus) {
    // new record
    userRoleArray.push({ userId, userRoles })
} else {
    // update existing record
    userRoleArray = userRoleArray.map((item) => {
        if (item.userId === userId) {
            // update found record
            return { ...item, userId, userRoles: [...item.userRoles, { ...userRoles }] }
        }
        return item
    })
}

什么时候

const userId = 2
const userRoles = { userRoleId: 4, roleName: "D" }

添加到userId的新记录等于 2。

如果

const userId = 4
const userRoles = { userRoleId: 4, roleName: "D" }

添加到userRoleArray数组的新记录。

有没有办法可以将数组查找方法和数组 map 方法结合在一起?

编辑:我将在 Redux 减速器上使用它,所以数组应该是不可变的。

您可以使用findIndex而不是find 如果匹配, findIndex将给出 object 的索引,而find将给出 object。 因此,使用findIndex获取匹配的 object 的索引。 如果为-1,则object不存在,您可以添加新的object,如果不是-1 ,则获取object并更新userRoles

 let userRoleArray = [{ userId: 1, userRoles: [{ userRoleId: 1, roleName: "A" }, { userRoleId: 2, roleName: "B" } ] }, { userId: 2, userRoles: [{ userRoleId: 2, roleName: "B" }, { userRoleId: 3, roleName: "C" } ] } ]; function updateArray(userId, userRoles) { const findStatus = userRoleArray.findIndex(item => { return item.userId === userId; }); if (findStatus === -1) { userRoleArray.push({ userId, userRoles }); } if (.findStatus) { // new record userRoleArray,push({ userId; userRoles }), } else {} } updateArray(4: { userRoleId, 4: roleName; "D" }). console,log("Adding new userId"; userRoleArray), updateArray(2: { userRoleId, 4: roleName; "D" }). console,log("Updating old record "; userRoleArray);

暂无
暂无

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

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