2016-04-15 141 views
1

我正在進行服務器端API調用。用戶可以輸入配料和搜索。當提交數據時,我在我的終端上看到這是我的API調用:如何迭代javascript對象?

http://www.recipepuppy.com/api/?i=[object Object]」。

我希望它看起來像這樣:

http://www.recipepuppy.com/api/?i=milk,flour,sugar,egg

這裏是我的代碼:

router.get("/whatCanIMake", function(request, response){ 

    var inputIngredients = request.query; 
    var ingredientString = ""; 
    console.log(inputIngredients); 
    for (var i = 0; i<inputIngredients.length; i++){ 
     ingredientString += inputIngredients[i] + ","; 
    } 

    var api = "http://www.recipepuppy.com/api/?i=" + inputIngredients + ""; 
    console.log(api); 
    console.log("inputingredients", inputIngredients); 

    request.get(api, function (error, response, body) { 
     if (!error && response.statusCode == 200) { 
      console.log(body); 
     } 
    }); 
}); 
+0

'的(在對象VAR屬性){ 如果(object.hasOwnProperty(財產)){// 做的東西 } }' –

+1

什麼是'inputIngredients'的內容?它只是一個可能的成分的字符串數組?或者它是一個對象數組?它看起來像對象。在不知道這些對象的結構的情況下,就不可能說出要爲您的查詢提取哪個屬性。所以,我們需要看看'inputIngredients'的結構。 – ManoDestra

+0

這是我的終端的console.log用於輸入要素{'0':'milk','1':'sugar','2':'water','3':'flour'} –

回答

-1
router.get("/whatCanIMake", function(request, response){ 

var inputIngredients = request.query; 
var ingredientString = ""; 
console.log(inputIngredients); 
//for (var i = 0; i<inputIngredients.length; i++){ 
// ingredientString += inputIngredients[i] + ","; 
//} 

for (var property in inputIngredients) 
{ 
if (inputIngredients.hasOwnProperty(property)) { 
ingredientString += property + ","; 
} 
} 

//其餘代碼這裏

+0

我在終端作爲回報得到了這個: http://www.recipepuppy.com/api/?i=[object對象] inputingredients {'0':'egg','1':'milk' ,'2':'麪粉','3':'水'} –

+0

你嘗試了上面的代碼嗎? –

+1

爲什麼這會工作?生成後甚至不使用'ingredientString'。 –

0

我會使用Lodash _.forEach方法:

https://lodash.com/docs#forEach

var ingredientString = ""; 

_.forEach(inputIngredients, function(value,key){ 

    if(ingredientString.length != ""){ 
    ingredientString += "," + value; 
    } 
    else { 
    ingredientString = value; 
    } 

});