Search code examples
javascriptzapier

Access member of an array javascript [zapier]


Im trying to access a key and its value in an array. You cansee from the code below I pus into the array the fieldName and the fieldValueCleaned - This is after doing some cleanup on the information passed through. I know that one of the fieldNames is myKey This and its value are being pushed into the array (I can see this from the console.log(fieldName +" : "+ fieldValueCleaned);) However, when I try to access the value directly as in itemArray.myKey, I get 'undefined'. Where am I going wrong

var itemArray = new Array();
var fields = new Array();
var fieldName;
var fieldValue;
var fieldValueCleaned;
for(var i = 0; i < types.length; i++){

  fields = types[i].split("=");
  fieldName = fields[0];
  fieldValue = decodeURIComponent(fields[1]);
  fieldValueCleaned = CleanUp(fieldValue);
  itemArray.push({[fieldName]: fieldValueCleaned}); 
console.log(fieldName +" : "+ fieldValueCleaned);
  console.log(itemArray.myKey);
}

Thanks in advance


Solution

  • What you're doing here is pushing objects into an array, not setting any keys. Your array ends up looking something like this:

    [
      { myKey: "value" },
      { myOtherKey: "value" }
    ]
    

    To put it simple, an array doesn't have keys (*), it has indices. Your keys are part of the object you pushed to the array, not of the array itself.

    What you want for your use case is a plain object, where you can set any keys you like. Change your code like this:

    var itemObject = {};
    var fields;
    var fieldName;
    var fieldValue;
    var fieldValueCleaned;
    for(var i = 0; i < types.length; i++){
    
      fields = types[i].split("=");
      fieldName = fields[0];
      fieldValue = decodeURIComponent(fields[1]);
      fieldValueCleaned = CleanUp(fieldValue);
    
      itemObject[fieldName] = fieldValueCleaned; 
    
      console.log(fieldName +" : "+ fieldValueCleaned);
    }
    console.log(itemObject.myKey);
    

    *: Technically, an array does have keys, as an array in Javascript is a type of object with special syntax. However, arrays are designed to work with keys that are integer indices. So while it's possible to set your own keys on an array, it serves little purpose and I can't think of many use cases where an array makes more sense than a plain object.