0
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?

2
  • Your data format is wrong from a JSON point of view. It's not really illegal ... but you will automatically end up with only one key/value pair out of 2, because JSON keys (on the same level) need to be unique Commented May 13, 2014 at 17:30
  • 1
    data should be an array of objects. Like [{"name":"RYI","id":2},{"name":"BIB","id":1}] Commented May 13, 2014 at 17:31

2 Answers 2

2
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.

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

Comments

0

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;
}

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.