skip to Main Content

I am trying to write a script to batch update products in a Woocommerce store via Rest API. API requires to send request as a JSON object, but I can’t build the Object in the necessarily format.

Object should look like this:

'{
"update": [
    {
      "id": 799,
      "name": "product name"
    },
    {
      "id": 800,
      "name": "product name 1"
    }
]
}'

I am trying to build the Object the following way, but it doesn’t work:

var APIPayloadObject = {update:[]};

//starting loop
for ( i = 0; i < lastrow; i++){
   var product = [];
   product.push({
      id: loopRange[i][0],
      name: loopRange[i][1]
   })

   //???????

}
Logger.log(JSON.stringify(APIPayloadObject));

At question marks I don’t know how to push product array into the object

2

Answers


  1. Sample 1

    As mentioned in my comment, the first solution is to access the update property and invoke push() on it since you already defined update to contain an Array instance:

    //starting loop
    for ( i = 0; i < lastrow; i++){
       APIPayloadObject.update.push({
          id:   loopRange[i][0],
          name: loopRange[i][1]
       })
    }
    

    Sample 2

    You can take it one step further and directly write your objects to update Array at the i index, since you start from 0:

    //starting loop
    for ( i = 0; i < lastrow; i++){
       APIPayloadObject.update[i] = {
          id:   loopRange[i][0],
          name: loopRange[i][1]
       };
    }
    
    Login or Signup to reply.
  2. This is a great use case for Array.prototype.map.

    // @param {sheetValues[][]} loopRange
    function getPayload(loopRange) {
      return JSON.stringify({
        update: loopRange.map(function (row) {
          return {id: row[0], name: row[1]};
        })
      });
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search