gpt4 book ai didi

javascript - 如何修改数组中对象的属性

转载 作者:行者123 更新时间:2023-11-29 17:54:38 28 4
gpt4 key购买 nike

首先请注意,这是我的 Redux 代码中的一个问题 HERE .

好吧,假设我想将“状态”的属性从“待定”编辑为“已删除”,再到数组中对象的特定属性,我将如何使用 Object.Assign 来完成此操作以下示例:

示例 a:(注意对象数组存储在对象本身中)

const plan = {
task: [
{
id: 1,
description: "This is a task",
status: "pending"
},
{
id: 2,
description: "This is a second task",
status: "pending"
}
]
}

示例 b:(元素为对象的简单元素数组)

const task2 = [
{
id: 1,
description: "This is a task",
status: "pending"
},
{
id: 2,
description: "This is a second task",
status: "pending"
}
]

最佳答案

好问题。您打算做的态射通常称为透镜(实际上是更大的态射组)。

你可以用纯JavaScript来实现,例如:

// Return a new object with the very same structure as plan and an amended list of tasks
return Object.assign({}, plan, {
tasks: plan.tasks.map(function (task) {
// Map every existing task to a totally new object with the very same structure and a new status
return Object.assign({}, task, { status: "deleted" })
})
})

第二个例子更容易变形,检查下面的代码:

return task2.map(function (task) {
// Return a totally new object with the very same structure as task and a new status
return Object.assign({}, task, { status: "deleted" });
})

此外,还有一些库可以完全满足您的需求,例如nanoscope

关于javascript - 如何修改数组中对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40419180/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com