0

i have a product array and customer array

and i want to add all customer array objects to the product array

    let product = [
      {image:"image1",id:0},
      {image:"image2",id:1},
      {image:"image3",id:2},
      {image:"image4",id:3},
      {image:"image5",id:4}
    ];
    let customer = [
      {user_id:11},
      {user_id:12},
      {user_id:13},
      {user_id:14},
      {user_id:15}
    ];

I want this array

    let product = [
      {image:"image1",id:0,user_id:11},
      {image:"image2",id:1,user_id:12},
      {image:"image3",id:2,user_id:13},
      {image:"image4",id:3,user_id:14},
      {image:"image5",id:4,user_id:15}
    ];
5
  • Concat them by array.concat() developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Dec 21, 2019 at 14:02
  • What have you tried so far to solve this on your own? A loop should be enough to solve this. Commented Dec 21, 2019 at 14:03
  • let ar3 = product.concat(customer) Commented Dec 21, 2019 at 14:03
  • @YAKA concat is not my answer Commented Dec 21, 2019 at 14:09
  • Your edit still calls for a simple loop. We are not here to do your homework. So please add what you have tried so far, what problems you have, any errors, ... Commented Dec 21, 2019 at 14:46

2 Answers 2

1

Since there is no clear relationship between customer, you can do this way

product = product.map((productItem, index) => ({
    ...productItem,
    user_id: customer[index].user_id
}));

which will output,

[
   {
      "image":"image1",
      "id":0,
      "user_id":11
   },
   {
      "image":"image2",
      "id":1,
      "user_id":12
   },
   {
      "image":"image3",
      "id":2,
      "user_id":13
   },
   {
      "image":"image4",
      "id":3,
      "user_id":14
   },
   {
      "image":"image5",
      "id":4,
      "user_id":15
   }
]
Sign up to request clarification or add additional context in comments.

Comments

0
product.forEach((x, index) => Object.assign(x, customer[index]));

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.