Home > Net >  For loop not iterating a variable
For loop not iterating a variable

Time:12-24

I'm just learning javascript and I'm trying to update woocommerce products through GAS.

The issue in question is the following:

I have a variable that parses the response from woocommerce

for (let sku of skuSearch) {
    var surl = website   "/wp-json/wc/v3/products?consumer_key="   ck   "&consumer_secret="   cs   "&sku="   sku;
    var url = surl
    Logger.log(url)

    var result = UrlFetchApp.fetch(url, optionsGet);
    if (result.getResponseCode() == 200) {

        var wooProducts = JSON.parse(result.getContentText());
        Logger.log(result.getContentText());

    }

Then I have another for to iterate and from a new array that contains id sku of wooProducts and price from a different variable that takes the updated price from my sheet:

var idLength = wooProducts.length;
    Logger.log(idLength);
    for (var i = 0; i < idLength; i  ) {
        var container = [];
        Logger.log(i);
        container.push({
            id: wooProducts[i]["id"],
            sku: wooProducts[i]["sku"],
            price: data[i]["price"],
        });

I can't tell exactly why it doesn't work. I mean the for loop works, it pushes id, sku and price in every loop, it's just that data[i] only provides the first ¿object? instead of looping like wooProducts which add 1 at every loop.

I'll copy 3 loops so it's crystal clear, I'm not sure it's already clear.

Loop 1:

[{"id":1622,"sku":"PD-1000-B","price":8145.9}]

Loop 2:

[{"id":1624,"sku":"PD-1007-A","price":8145.9}]

Loop 3:

[{"id":1625,"sku":"PD-1014","price":8145.9}]

As you can see id sku change but price doesn't.

For further context, I'll include the data variable that is declaed outside the For:

const data = codigos.map(function(codigos, indice) {
    return {
        sku: codigos[0],
        price: precios[indice][0]
    }
})

//** EDIT:

I'm adding the entire code so it makes more sense maybe?

function getDataloopwoo() {
var ck = 'xxx'

var cs = 'xxx'

var website = 'xxx'

var optionsGet =

    {
        "method": "GET",
        "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
        "muteHttpExceptions": true,

    };    

var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('PreciosBULK');
var codigos = sheet.getRange("A2:A").getValues();
var precios = sheet.getRange("B2:B").getValues();
var skuSearch = sheet.getRange("A2:A").getValues();

const data = codigos.map(function(codigos, indice) {
    return {
        sku: codigos[0],
        price: precios[indice][0]
    }
})
Logger.log(skuSearch)

for (let sku of skuSearch) {
    var surl = website   "/wp-json/wc/v3/products?consumer_key="   ck   "&consumer_secret="   cs   "&sku="   sku;
    var url = surl
    Logger.log(url)

    var result = UrlFetchApp.fetch(url, optionsGet);
    if (result.getResponseCode() == 200) {

        var wooProducts = JSON.parse(result.getContentText());
        Logger.log(result.getContentText());

    }
    var idLength = wooProducts.length;
    Logger.log(idLength);
    var container = [];
    for (var i = 0; i < idLength; i  ) {            
        Logger.log(i);
        container.push({
            id: wooProducts[i]["id"],
            sku: wooProducts[i]["sku"],
            price: data[i]["price"],
        });
        
        Logger.log(container);
        var wooBatch = JSON.stringify(container);
        Logger.log(wooBatch);           
      }        
}

}

// FINAL EDIT with "solve":

So I figured it was inefficient to ask by 1 sku at a time, so now I'm asking by the 100, and paginating with a while if and saving id, sku, price to the container array. I will need now to compare the container array to the array with the updated prices and form a new array with id, sku and updated price, I'm reading up on that right now. The code:

function getDataloopwoo() {
var ck = 'xx'

var cs = 'xx'

var website = 'xx'

var optionsGet =

    {
        "method": "GET",
        "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
        "muteHttpExceptions": true,

    };    

var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('PreciosBULK');
var codigos = sheet.getRange("A2:A").getValues();
var precios = sheet.getRange("B2:B").getValues();    

const data = codigos.map(function(codigos, indice) {
    return {
        sku: codigos[0],
        price: precios[indice][0]
    }
})


var container = [];


    var surl = website   "/wp-json/wc/v3/products?consumer_key="   ck   "&consumer_secret="   cs   "&per_page=100";
    var url = surl
    //Logger.log(url)

    var result = UrlFetchApp.fetch(url, optionsGet);
    var headers = result.getAllHeaders();
    var total_pages = headers['x-wp-totalpages'];
    var pages_count = 0;
    while (pages_count < total_pages) {

    if (result.getResponseCode() == 200) {

        var wooProducts = JSON.parse(result.getContentText());
        //Logger.log(result.getContentText());
    }     
    
    
    for (var i = 0; i < wooProducts.length; i  ) {            
        //Logger.log(i);
        container.push({
            id: wooProducts[i]["id"],
            sku: wooProducts[i]["sku"],
            price: wooProducts[i]["price"],
        });
        
        Logger.log(container);            
        
      }
      pages_count  ;
      if (pages_count < total_pages){
        var surl = website   "/wp-json/wc/v3/products?consumer_key="   ck   "&consumer_secret="   cs   "&per_page=100"   "&page="   (pages_count   1);
        var url = surl
        var result = UrlFetchApp.fetch(url, optionsGet);
        Logger.log(url);
                    
      }        
}

}

CodePudding user response:

You're reseting the array container in every iteration of the loop:

for (var i = 0; i < idLength; i  ) {
    var container = []; // <-----------------here
    ...
    container.push({
    ...

I think the array should be defined outside the loop:

var container = [];
for (var i = 0; i < idLength; i  ) {
    ...
    container.push({
    ...
  • Related