I have a complex (or what I consider complex) function that I'm banging my head against the keyboard trying to create in google scripts.
I am managing 3 different objects. 1) sourceData 2) indexData 3) outputData
sourceData[29] | Array | [{type:"cat", count:"3"}, {type:"dog", count:"5"}...]
indexData[29] | Array | [{type:"cat", id:"301"}, {type:"dog", id:"302"}...]
outputData[29] | Array | [{type:"cat", id:"301", count:"3"}, {type:"dog", id:"302", count:"5"}...]
I am currently iterating through the source data using a for loop to create data in the outputData object.
for (var i = 0; i < sourceData.length; i++) {
var animals = {};
outputData.push(animals);
animal.type = sourceData[i].type;
animal.id = lib.indexMatch(indexData, sourceData[i].type);
animal.count = sourceData[i].count;
}
in this loop I call another function from my library called indexMatch.
function indexMatch(data, lookup) {
var index = data; // object that contains the data to iterate through.
for (var j = 0; j < index.length; j++){ // iterate through all rows in data
if(index[j][0]=lookup){
var value = index[j][1];
}
}
Logger.log(j);
return value;
}
Its purpose is to loop through the indexData and match the key parameter in the source data and output that data into the outputData sheet during the initial for loop.
However, all I am getting for animalId is undefined.
I was way overthinking this issue. I had to walk away from it and I certainly realised how simple the solution is:
function search(array, key, compareKey, valueKey){
for (var i=0; i < array.length; i++) {
if (array[i][compareKey] === key) {
return array[i][valueKey];
}
}
}