I have a JSON as follows:
{
"workloadId": "68cf9344-5a3c-4e4a-927c-c1c9b6e48ccc",
"elements": [
{
"name": "element1",
"uri": "vm/hpcloud/nova/large"
},
{
"name": "element2",
"uri": "vm/hpcloud/nova/small"
}
],
"workloadStatus": "none"
}
I need to get the comma seperated string as follows : element1,element2
when i tried as given below , i got empty string:
app.post('/pricingdetails', function(req, res) {
var workload = req.body;
var arr = new Array();
for(var index in workload.elements)
{
arr[index] = workload.elements[index].uri;
}
console.log(arr.join(","));
}
Elements is an array. Never use for/in for arrays. Use a standard for loop instead:
for(var i = 0; i < workload.elements.length; ++i) {
arr.push(workload.elements[i].uri);
}
console.log(arr.join(',');
Node will let you use the forEach method instead of a for loop or the for/in (the latter of which has the potential to cause problems).
Avoiding new Array() is another Crockford-ism, but I also just find the [] notation more concise and readable.
var workload = req.body;
var arr = [];
workload.elements.forEach(function(el) {
arr.push(el.uri);
});
console.log(arr.join(','));
These sort of nitpicks aside, like dc5 I tried just defining a variable with your JSON and your code did what I would expect (returning the array elements joined by a comma). What are you using to call that route, and how are you passing it the indicated JSON?
EDIT: using
curl -v -H "Content-type: application/json" -X POST -d '{"workloadId": "68cf9344-5a3c-4e4a-927c-c1c9b6e48ccc", "elements": [{"name": "element1", "uri": "vm/hpcloud/nova/large"}, {"name": "element2", "uri": "vm/hpcloud/nova/small"} ], "workloadStatus": "none"}' http://localhost:3000/pricingdetails
fails for me if bodyParser() isn't used. With app.use(express.bodyParser()); in my code, it works as expected.