0

I am running a loop over some data. I have an object with a key value message. Every time I loop over my array I want to append to this objects key value, I tried using spread operator but not having any luck

  const arr1 = [
    "keith",
    "kelly",
    "ed",
    "shelby"
]

const arr2 = [
    "Parker",
    "Morgan",
    "Arnold",
    "Suski",
    "Parks"
]

const addToObjectsMessageKey = arr1.map((name) => {
 let obj = {}
    arr2.forEach((lastName) => { return {...obj, message: ...obj.message + name}})
 return obj
})

console.log(addToObjectsMessageKey)

expected output

addObjectsToMessageKey = [
{ message: "Parker Morgan Arnold Suski Parks" },
{ message: "Parker Morgan Arnold Suski Parks" },
{ message: "Parker Morgan Arnold Suski Parks" },
{ message: "Parker Morgan Arnold Suski Parks" },
]
5
  • Unclear what you're trying to achieve. You want arr1.length times the concatenated output of arr2 in an object array? arr1.map(_ => ({message: arr2.join(' ')})) Commented Mar 29, 2022 at 2:51
  • Your code has an error SyntaxError: expected expression, got '...'" Commented Mar 29, 2022 at 2:54
  • also arr2.forEach((lastName) => { return { does nothing, since the returned value in a forEach is a GNDN Commented Mar 29, 2022 at 2:56
  • you seem to be overcomplicating your code, to get what you want is a case of const addToObjectsMessageKey = arr1.map(() => ({message: arr2.join(' ')})); Commented Mar 29, 2022 at 3:01
  • I asked the question with better detail here stackoverflow.com/questions/71658030/… Commented Mar 29, 2022 at 7:36

1 Answer 1

0

Looks like you want to overwrite the arr1 elements to an object with all the elements on the arr2 joined by space, you can simplify this using arr.join MDN documentation instead of forEach

const arr1 = ["keith", "kelly", "ed", "shelby"];

const arr2 = ["Parker", "Morgan", "Arnold", "Suski", "Parks"];

const addToObjectsMessageKey = arr1.map(() => {
  return {
    message: arr2.join(" ")
  };
});

console.log(addToObjectsMessageKey);

Here is a codeSandbox:

https://codesandbox.io/s/agitated-mestorf-tlhkh2?file=/src/index.js:0-248

Is this what you want?

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

2 Comments

I asked it better with more details here stackoverflow.com/questions/71658030/…
I see what you need, I added my go-to solution for those cases, Regex

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.