0

I have two arrays, orders and cartitems

I want to create a singel payload with information of both of arrays combined. to post to my API using Axios.

I've tried mapping one array (since I only need one item from the other array) and then trying to add the objects together like this:

const payload = []
let newArray = []

this.props.cartItems.map((item) => {
  let payloadobject = {
    productName: item.productname,
    amount: item.qty,
    price: item.price,
    order_id: this.props.cart.id,
  }

  newArray = appendObjTo(payload, payloadobject);
})

Hoping newArray would hold the combined combined array. But get met with the error:

can't find variable: appendObjTo

How do I combine both objects? That are each in side of their own array

edit

current data structure

catritems

cartItems Array [
  Object {
    "id": 2,
    "price": "6.50",
    "productname": "Baco",
    "qty": 2,

  }
]

orders

orders Array [
  Object {
    "id": 2,
  }
]

desired output

newArray Array [ Object { "id": 2, "price": "6.50", "productname": "Baco", "qty": 2, "order_id": 1 (hold id from order object), } ]

Salman
  • 1,109
  • 3
  • 25
  • 55

1 Answers1

1

You get the error message since appendObjTo isn't defined. It's not a standard function, and if you've defined it yourself it's probably in another scope.

Instead of appendObjTo you could use the Object.assign function (MDN Reference). It could be used like this:

newArray = Object.assign({}, payload, payloadobject);

However, there's another fault in your code. Right now your assigning each combined object to newArray, and at the en it will hold the last combined object, not an array.
The lambda function you supply to map should return a new object that you want to replace the input object in the new array. When all objects are looped through the map function returns a new array (MDN Reference). In your case it could be used like this:

const payload = [];

let newArray = this.props.cartItems.map((item) => {
    let payloadobject = {
        productName: item.productname,
        amount: item.qty,
        price: item.price,
        order_id: this.props.cart.id
    };

    return Object.assign({ }, payload, payloadobject);
});

This will make newArray be an array of object where each object is a combination of the whole payload, and payloadobject.

Hope this helps

Netråm
  • 453
  • 6
  • 12