如果我想附加到一个现有的数组属性,最干净的解决方案是什么?
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
的索引。
答案 0 :(得分:1)
要使用扩展语法附加到数组,您可以使用以下语法:
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']
}
)
答案 1 :(得分:1)
您可能希望避免在 access
中重复,并避免两次调用该函数,因此没有捷径可走。我建议:
function adminConditional(user) {
return {
...user,
priority: 1,
access: ['system2']
}
}
let user = adminConditional({name: "andrew", type: "Admin"});
console.log(
{
...user,
access: [...new Set(['system1', ...user.access])]
}
)
答案 2 :(得分:1)
你可以简化逻辑
function adminConditional(user) {
return {
...user,
priority: 1,
access: ['system2', ...user.access]
};
}
console.log(
{
...(adminConditional)({
name: "andrew",
type: "Admin",
access: ['system1']
})
}
)