Spdexter
Spdexter

Reputation: 933

Javascript storing objects in an array

function(data) {
    var lob = new LOBslist(); //new object
    var returnLOB = []; //array init
    for (var i1r= 0; i1r < data.length; i1r++) { 
        var cLob = data[i1r];
        lob.name = cLob.name;
        lob.id = cLob.id;

        returnLOB.push(lob); //adding to array?
        console.log(lob); //right here
  }

  console.log(returnLOB);
  return returnLOB;
}

data is in a format like

{"name":"RYI","id":2,"name":"BIB","id":1}

I want to access the above data, store each name and id in an object called lob and store each object in an array returnLOB.

Every time I loop through and console.log(lob), I get correct objects like: RYI id:2 and BIB id:1 then

but when I try to store them in the returnLOB array it outputs the second object twice rather than each object once.

Any idea what is wrong here?

Upvotes: 0

Views: 789

Answers (2)

Darrin Cullop
Darrin Cullop

Reputation: 1210

Try creating the lob object each time, otherwise you're just adding the same one over and over and changing it's values each time. Plus, your code could be simplified by using a "for...in" loop, as shown:

function(data) {
    var lob;
    var returnLOB = []; //array init
    for (var cLob in data) { 
            lob = new LOBslist(); //new object
            lob.name = cLob.name;
            lob.id = cLob.id;

            returnLOB.push(lob); //adding to array?
            console.log(lob); //right here
    }

    console.log(returnLOB);
    return returnLOB;
}

Upvotes: 0

TGH
TGH

Reputation: 39248

function(data) {
        var returnLOB = []; //array init
        for (var i1r= 0; i1r < data.length; i1r++) { 
                var lob = new LOBslist(); //new object
                var cLob = data[i1r];
                lob.name = cLob.name;
                lob.id = cLob.id;

                returnLOB.push(lob); //adding to array?
                console.log(lob); //right here

        }

        console.log(returnLOB);
        return returnLOB;

    }

Move the declaration of lob into the loop. Right now you are reusing the same object and adding it to the array multiple times. Each time through the loop the same object is updated.

Upvotes: 2

Related Questions