0

So, my code goes like this:

  await axios
    .get(UrlGetOrderItems)
    .then((response) => {
      let arr = response.data.data.orders;
      if (arr.length) {
        getOrdersFromAPI = [];
        arr.forEach((order) => {
          let colName = order.order_id;
          getOrdersFromAPI.push({
            colName: {
              voucher: order.voucher,
              price: parseFloat(order.price),
              shipping_fee: order.shipping_fee,
            }
          });
        });
      }
    })

But results to the array being named as "colName"

  {
    colName: {
      voucher: 50,
      price: 1,
      shipping_fee: 42,
      subtotal: 1982,
    }
  }

How do I call the variable instead of the string 'colName'? I tried backticks (${colName}) but results in an error. I'm using node js for this. Any ideas? Thanks in advance!

2 Answers2

1

Just use symbol instead of colName as string...

 await axios
    .get(UrlGetOrderItems)
    .then((response) => {
      let arr = response.data.data.orders;
      if (arr.length) {
        getOrdersFromAPI = [];
        arr.forEach((order) => {
          let colName = order.order_id;
          getOrdersFromAPI.push({
            [colName]: {
              voucher: order.voucher,
              price: parseFloat(order.price),
              shipping_fee: order.shipping_fee,
            }
          });
        });
      }
    })
user2349470
  • 198
  • 8
0

try this.

const arr = [{
  order_id: "1",
  voucher: "v",
  price: "10.0",
  shipping_fee: 10
}]

const getOrdersFromAPI = arr.map(order => {
  const obj = {};
  obj[order.order_id] = {
    voucher: order.voucher,
    price: parseFloat(order.price),
    shipping_fee: order.shipping_fee,
  };
  return obj;
});

console.log(getOrdersFromAPI);
D. Seah
  • 4,472
  • 1
  • 12
  • 20