0

Let's say I have an object like

const team = {
  name: "something",
  members: [1, 2, 3],
};

and in the above object I want to append the value 4 to the array?

would this be acceptable code?

const newTeam = { ...team, members: team.members.concat(userId) };

I am using concat because it does not modify the array and I don't think I have to use map in this instance. Is my thinking, correct?

Peter Seliger
  • 11,747
  • 3
  • 28
  • 37
iJK
  • 4,655
  • 12
  • 63
  • 95
  • 3
    Yes. You could also use array spread: `members: [...team.members, userId]` – Felix Kling Apr 05 '21 at 15:09
  • @FelixKling Thank you, for the confirmation! – iJK Apr 05 '21 at 15:14
  • The Q. itself, at least in JS, is a contradiction. *"Append to an array"* implies (or pretty much sounds like) the mutation of exactly that array. And even though both approaches are straightforward and clean, I don't see anything *(purely) functional* related in it. The problem as well as the solution(s) pretty much read like ... *How reliable is spread syntax for cloning a certain (or this specific) object structure?* – Peter Seliger Apr 05 '21 at 15:35

0 Answers0