1

I send a get request to the api wichh returns data under form of

{
"message": "<SUCCESS>",
"result": [
{
  "i": 1,
},
{
  "i": 2,
},    
{
  "i": 3,
}  ]
}

Then in javascript (angular component.ts) I want to create an array ob objects but after pushing the objects in the array every array contains the data of the last object:

.subscribe(
          data => {
            type MyArrayType = Array<UserOpinion>;
            let array: MyArrayType = [];
            let cont: CustomInterface = {
              i: ''
            }

            data.result.forEach(function(entry) {
            cont.i = entry["i"];

            array.push(cont);
            console.log(cont);
            //right value is shown

            })
            //console.log(array)
            //array contains the connect number of objects but the objects are set on the             same value: "i" = 3

Any ideas why this happens? Thank you

1 Answers1

0

This should do it:

.subscribe(
    data => {
        type MyArrayType = Array<UserOpinion>;
        let array: MyArrayType = [];

        data.result.forEach(function(entry) {
            array.push(entry);
        });
    }
);

You dont need cont just for copying the current object to another, you can use the current loop element directly.

Abhay Maurya
  • 11,819
  • 8
  • 46
  • 64