-3

I have an array that contains cameras specifications, the problem occurs when I try to run a for loop to get the elements.

Here is the content of my array :

enter image description here

I tried all different types of for loops like forEach, basic for loop with increment or for (let item of myArray)

For loop doesn't run and I have no return of the element in the array.

for (let id in elements) {

      if (typeof elements[id].brands !== 'undefined') {

        delete this.items;

        let itemsArray = [];

        for (let elementData of elements[id].brands) {

          this.http.get("assets/data/" + elementData + "Reflex.json").map(res => res.json()).subscribe(data => {

            Array.prototype.push.apply(itemsArray, data);

          });

        }

        this.items = itemsArray;

      }

      if (typeof elements[id].sensorSize !== 'undefined') {


      }

    }

(this.items is the array that you can see on the top (I use Angular2)).

Alvin FREY
  • 43
  • 11

2 Answers2

0

Try this code, it will iterate on the array itself and return all items in it as objects in the inline function.

this.items.forEach( function (item)
{
 item.xxx=11;
} );
Miro Krsjak
  • 355
  • 1
  • 16
0
  this.http.get("assets/data/" + elementData + "Reflex.json").map(res => res.json()).subscribe(data => {

    Array.prototype.push.apply(itemsArray, data);

  });

This call is the problem.It is asynchronous.

The for loop will not wait for the response to push data into itemArray. A rough way to get the array is:

      this.http.get("assets/data/" + elementData + "Reflex.json").map(res => res.json()).subscribe(data => {

        Array.prototype.push.apply(this.items, data);//make sure this.items is set to empty previous to call

      });
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103