2017-04-03 154 views
0

匹配值我有一個複雜的(或者我認爲複雜的)那我敲我的頭靠在鍵盤試圖在谷歌腳本來創建功能。循環通過一個對象,並在另一個對象

我管理3個不同的對象。 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"}...] 

我目前通過源數據使用for循環以在outputData對象數據進行迭代。

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; 
 
}

在這個循環中我把從我的庫的另一個函數調用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; 
 
}

它的目的是通過indexData環和在源數據中的關鍵參數和輸出匹配數據到初始for循環期間outputData片。

然而,所有我得到了animalId是不確定的。

我得太多方式這個問題。我不得不離開它,我當然認識到解決方案是多麼簡單:

function search(array, key, compareKey, valueKey){ 
 
    
 
    for (var i=0; i < array.length; i++) { 
 
     if (array[i][compareKey] === key) { 
 
      return array[i][valueKey]; 
 
     } 
 
    } 
 
}

+0

在與谷歌的腳本工作,總是谷歌在JavaScript的解決方案。谷歌腳本支持javascript功能,其中大部分是。對於你的情況下,你可能想開始[這裏](http://stackoverflow.com/questions/1168807/how-can-i-add-a-key-value-pair-to-a-javascript-object) –

+0

你的哪裏代碼和問題是什麼? –

回答

0

我明白,你想從outputDatasourceDataindexData。如果我誤解了你的問題,我很抱歉。

下面的示例如何?

樣品:

function myFunction() { 
    var sourceData = [{type:"cat", count:"3"}, {type:"dog", count:"5"}]; 
    var indexData = [{type:"cat", id:"301"}, {type:"dog", id:"302"}]; 
    var outputData = []; 

    sourceData.forEach(function(e){ 
    indexData.forEach(function(f){ 
     if (e.type == f.type) { 
     var dic = { 
      type: f.type, 
      id: f.id, 
      count: e.count 
     }; 
     outputData.push(dic);  
     } 
    }); 
    }); 
} 

結果:

>>> [{count=3, id=301, type=cat}, {count=5, id=302, type=dog}] 

關於你的腳本:

  1. 在腳本中,name被用作密鑰。但是sourceDataindexData沒有鑰匙。因此idtype在outputData中變成null

  2. indexMatch()index是一個維陣列。所以index[j][0]總是undefined

  3. 關鍵count不被使用。

相關問題