angular.forEach返回对象数组重复相同的对象

时间:2023-02-05 02:32:44

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.

我有一个包含5个对象的数组,我需要循环并返回一个对象数组。但是,当我这样做时,它只返回最后一个对象5次。

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)

不起作用:(循环对象并返回一个对象,但只将最后一个推送到数组5次)

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

1 个解决方案

#1


0  

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

我认为问题在于你的getDataFromObject方法。该方法的代码是什么?

#1


0  

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

我认为问题在于你的getDataFromObject方法。该方法的代码是什么?