0

I am preparing JSON data to send a POST request. I have an array like ['2051','2052]. I want to pass these two ID's into the JSON object. Here's my required JSON data :

 var arr =['2051','2052']
 var bData = {
      "product_id": 2,
      "cart_item_data": 
      {
        "wc_bookings_field_duration": 5,
        "wc_bookings_field_start_date_year": 2021,
        "wc_bookings_field_start_date_month": 05,
        "wc_bookings_field_start_date_day": 28,
        "wc_bookings_field_start_date_time": 09:00,
        "wc_bookings_field_start_date_local_timezone": "",
        "add-to-cart": 2,
        "start_time": 09:00,
        "end_time": 5,
        `wc_bookings_field_persons_2051`: 5,
        `wc_bookings_field_persons_2052`: 0,
      },
    }

And here's what i have tried :

 var arr =['2051','2052']
 var personStr = arr[0].toString()
 var childStr = arr[1].toString()
 var bData = {
      "product_id": 2,
      "cart_item_data": 
      {
        "wc_bookings_field_duration": 5,
        "wc_bookings_field_start_date_year": 2021,
        "wc_bookings_field_start_date_month": 05,
        "wc_bookings_field_start_date_day": 28,
        "wc_bookings_field_start_date_time": 09:00,
        "wc_bookings_field_start_date_local_timezone": "",
        "add-to-cart": 2,
        "start_time": 09:00,
        "end_time": 5,
        `wc_bookings_field_persons_${personStr}`: 5,
        `wc_bookings_field_persons_${childStr}`: 0,
      },
    }

But this is throwing unexpected token for some reason. What am i doing wrong here? Also the number of items in the array might be more. Then more items will add in the object.

we Devs
  • 3
  • 2
  • You can use computed property names: `[\`wc_bookings_field_persons_${personStr}\`]: 5` – Nick Parsons May 09 '21 at 07:05
  • You cannot use template literals inside object literals for property names, that throws `Uncaught SyntaxError: expected property name, got template literal`. – connexo May 09 '21 at 07:09
  • It shows only the first field_persons when i try your way. Don't know why's that @NickParsons – we Devs May 09 '21 at 18:59

1 Answers1

0

You can use bData.cart_item_data["wc_bookings_field_persons_" + personStr] = 5 in order to have dynamic reading.

object.hello is same as object['hello'] in JavaScript