0

what I want to achieve is filling the array "presents" with the value of arr when name is "Mario" in this case, what I get is the array "present" modify, but what I want is an non mutative array, only change the value of the empty array with the value of another array(in this case I put arr as example)

let present= [
    {
      name: "Peter",
      presents: []
    },
    {
      name: "Mario",
      presents: []
    },
    {
      name: "Amanda",
      presents: []
    },
    {
      name: "David",
      presents: []
    }
]
arr = ["car","coal"]

const res= present.map(s =>s.name == "Mario" ? s.presents.concat(arr) : [])

console.log(res)

What I want to get:

let present= [
    {
      name: "Peter",
      presents: []
    },
    {
      name: "Mario",
      presents: ["car","coal"]
    },
    {
      name: "Amanda",
      presents: []
    },
    {
      name: "David",
      presents: []
    }
]

pd: sorry , I could not explain better, still learning English.

2 Answers 2

1

You can do the following using reduce(),

const present = [{ name: "Peter", presents: [] }, { name: "Mario", presents: [] }, { name: "Amanda", presents: [] }, { name: "David", presents: [] } ],
arr = ["car", "coal"],

res = present.reduce((prev, curr) => {
  if(curr.name === 'Mario') {
    prev.push({...curr, presents: [...curr.presents, ...arr]})
  } else {
    prev.push(curr);
  }
  return prev;
}, []);
console.log(res);

Sign up to request clarification or add additional context in comments.

Comments

1

You could spread the objects and add the wanted array.

const
    present = [{ name: "Peter", presents: [] }, { name: "Mario", presents: [] }, { name: "Amanda", presents: [] }, { name: "David", presents: [] } ],
    array = ["car", "coal"],
    result = present.map(({ presents, ...o }) => ({
        ...o,
        presents: [...presents, ...(o.name === "Mario" ? array : [])]
    }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.