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.

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

1 Answer 1

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

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

5 Comments

You cannot use the ${expression} syntax outside of template literals.
Oops, I am sorry. You should write only personStr
Then what about childStr @AtheeshThirumalairajan
Do the same i.e., bData.cart_item_data["wc_bookings_field_persons_" + childStr] = 0
bData.cart_item_data["wc_bookings_field_persons_" + personStr] = 5 only shows the first item. How to get both of them actually @AtheeshThirumalairajan

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.