2016-04-15 143 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; 
    } 

});