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(","));
}
2
  • 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? Commented Jul 22, 2013 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. Commented Jul 22, 2013 at 17:49

2 Answers 2

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(','));
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.