1

My NodeJs code that uses request is as follows:

var objIdArr    = [obj1, obj2, obj3];
var index = 0;
var result = {};
var resultArr = [];

(function deleteRecur(){

    if (index > objIdArr.length-1) {
    //we are done iterating
        console.log(resultArr); //faulty resulte

    } else
        {       
      request(        //nodejs request module          
          {   
             uri: base_uri + '/' + objIdArr[index],
             method: 'DELETE',
             headers: headers
         },   

           function(error, response, body) {

                var arg = (transMap.get(objType)).res[0];
                if (!error && response.statusCode == 200) {
                    result['vmid'] = objIdArr[index];
                    result["result"] = "Success";
                } else{
                    result['vmid'] = objIdArr[index];
                    result["result"] = "failure";
                    result["detail"] = error;
                } 
                resultArr[index] = result;
                index++;
                deleteRecur();
        });
    }

}());

Expected resultArr [{ vmid: 'obj1', result: 'OK' },{ vmid: 'obj2', result: 'OK' },{ vmid: 'obj3', result: 'OK'}].

But console.log prints [{ vmid: 'obj3', result: 'OK' },{ vmid: 'obj3', result: 'OK' },{ vmid: 'obj3', result: 'OK'}].

Seems like whenever I change result elsewhere in the code, its affecting the array resultArr too. How is this possible? Isnt javascript supposed to be pass by value?

How do I resolve this?

1
  • I couldnt think of a better question title. Please feel free to edit it. Commented Mar 9, 2014 at 18:05

1 Answer 1

2

Create var result = {}; inside the function where you use it and push it into resultArr. Currently you are overwriting the data each time (the array contains the same object multiple times instead of multiple objects).

Sign up to request clarification or add additional context in comments.

3 Comments

Hey Wain, can you tell me, why the first object in the FIDDLE jsfiddle.net/TRNCFRMCN/6b2kM already has the number of elements of the array, and the indexes 0-3?
@dollarVar I don't understand your question
Yeah, I thought so...ehhmm, look at the picture here. In the first console.loged object is basically the same as in the last objects, and the index in the first object is already at zero until three... :/ Understandable? :D

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.