If I want to append to an existing property that’s an array, what’s the cleanest solution?
JavaScript
x
30
30
1
function adminConditional(user) {
2
return {
3
user,
4
priority: 1,
5
access: ['system2']
6
}
7
}
8
9
console.log(
10
{
11
adminConditional)({name: "andrew", type: "Admin"}), // function name can vary (
12
access: ['system1'] // always set
13
}
14
)
15
16
// Expected output:
17
{
18
access: ["system1", "system2"],
19
name: "andrew",
20
priority: 1,
21
type: "Admin"
22
}
23
// Actual output:
24
{
25
access: ["system1"],
26
name: "andrew",
27
priority: 1,
28
type: "Admin"
29
}
30
It instead overwrites the index of access
with the last assignment.
Advertisement
Answer
You can simplify logic
JavaScript
1
17
17
1
function adminConditional(user) {
2
return {
3
user,
4
priority: 1,
5
access: ['system2', user.access]
6
};
7
}
8
9
console.log(
10
{
11
adminConditional)({ (
12
name: "andrew",
13
type: "Admin",
14
access: ['system1']
15
})
16
}
17
)