javascript - 在对象中合并具有相同键的数组属性
问题描述
如果我想附加到一个现有的数组属性,最干净的解决方案是什么?
function adminConditional(user) {
return {
...user,
priority: 1,
access: ['system2']
}
}
console.log(
{
...(adminConditional)({name: "andrew", type: "Admin"}), // function name can vary
access: ['system1'] // always set
}
)
// Expected output:
{
access: ["system1", "system2"],
name: "andrew",
priority: 1,
type: "Admin"
}
// Actual output:
{
access: ["system1"],
name: "andrew",
priority: 1,
type: "Admin"
}
access
相反,它会用最后一个赋值覆盖索引。
解决方案
要使用扩展语法附加到数组,您可以使用以下语法:
let arr = [1,2,3];
let newArr = [...arr, 4];
newArr 将包含[1,2,3,4]
. 同样可以在对象中应用,只需使用扩展运算符将属性引用到函数中,就可以获得相同的结果:
function adminConditional(user) {
return {
...user,
priority: 1,
access: ['system2']
}
}
console.log(
{
...(adminConditional)({name: "andrew", type: "Admin"}),
access: [...(adminConditional)({name: "andrew", type: "Admin"}).access, 'system1']
}
)
推荐阅读
- powershell - 我怎样才能运行一个批处理文件大约 1000 次,然后我想要平均执行时间作为输出。这可能吗?
- angular - 在 dropzone 中显示图像列表
- reporting-services - 将 db2 存储过程导入 SSRS 时出错
- rust - 具有拥有和借用值的“if”分支,没有 let 绑定
- python - 在python中使用模除的numpy.poly1d查找方程的根
- java - java.io.InvalidClassException: cdfs.events.C; 本地类不兼容:流 classdesc serialVersionUID = -x,本地类 serialVersionUID = y
- nginx - NGINX 无法访问此站点
- clang - 宏预处理时ClangTool解析代码短路评估不起作用
- python - 我如何使用 python 用特定标签标记特定卖家
- ios - 如何在 iOS 中使用多个注释来增加 Apple Mapkit 的缩放