0

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(","));
}
dc5
  • 12,341
  • 2
  • 35
  • 47
Prem
  • 5,685
  • 15
  • 52
  • 95
  • You could console.log arr[index] after each row in the loop. it doesn't seem wrong at first glance, except that perhaps workload is not a json object, but a string itself? – Alexander Olsson Jul 22 '13 at 17:45
  • Assigning the JSON listed above directly to workload works as expected. Looks like the error may be in the assignment. Instead of workload = req.body, try assigning the response to workload. – dc5 Jul 22 '13 at 17:49

2 Answers2

1

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(','));
opHASnoNAME
  • 20,224
  • 26
  • 98
  • 143
Chris Tavares
  • 29,165
  • 4
  • 46
  • 63
0

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.

Community
  • 1
  • 1
max
  • 5,979
  • 2
  • 21
  • 16