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
Sample 1
As mentioned in my comment, the first solution is to access the
update
property and invokepush()
on it since you already definedupdate
to contain anArray
instance:Sample 2
You can take it one step further and directly write your objects to
update
Array at thei
index, since you start from 0:This is a great use case for Array.prototype.map.