0

I have an array of 5 objects that i need to loop through and return in an array of objects. However when i do that, it only returns the last object 5 times.

I've got two pieces of code doing pretty much the exact same thing one works where as another doesn't.

working code: (loops through a string, splits on | and returns an object in an array);

angular.forEach(exampleString, function(data) {
    if (data.indexOf('|') !== -1) {
        data = data.split('|');
        //self.model.getDataFromArray()returns an object
        newArray.push(new self.model.getDataFromArray(data));
    }
});

//returns array of objects

doesn't work: (loops through objects and returns an object but only pushes the last 1 to the array 5 times)

angular.forEach(exampleObjects, function(data) {
    this.push(new self.model.getDataFromObject(data));
}, newArray);

Is there anything that i'm doing or not doing that is causing this to fail? the only real difference i can tell is that i start with a string that i split as opposed to starting with an object.

just to clarify if i do the following i get the same repetition:

 angular.forEach(exampleObjects, function(data) {
    newArray.push(new self.model.getDataFromObject(data));
});
2
  • is the exampleString a string? or is it an array?? Your assessment "loops through a string" is incorrect, the first parameter of your foreach is supposed to be an object/array you iterate over. You don't iterate over a string value. Commented Oct 16, 2015 at 20:10
  • @sksallaj sorry yeah, it's an array of strings. Commented Oct 19, 2015 at 9:10

1 Answer 1

0

I think the problem lays in your getDataFromObject method. What is the code in that method?

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

2 Comments

getDataFromObject(data) { var obj = {}; obj = data; obj.attr1 = data.attr1; obj.attr2 = data.attr2; return obj; } just simple mapping, exactly the same as the other working method
what seemed to work for me was changing var obj = {}; to self.obj = {}; not sure why it makes a difference

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.