3

I wonder how to create an object inside the foreach? Without posting here all my code, in my case, I cannot declare the object outside of the foreach (using react and doing that insight my render function which leads to weird results). How can I do that? Thanks!

    var list;
    this.state.resp.forEach(function(e) {
       list[e.OriginLocation.AirportCode] = e.OriginLocation.CityName;
    });
Iman Bahrampour
  • 6,180
  • 2
  • 41
  • 64
javascript2016
  • 973
  • 3
  • 17
  • 41
  • Well, you can't declare it inside the forEach unless you want to re-declare it every iteration. Can you assign to a new variable? – Sterling Archer Dec 15 '17 at 16:07

2 Answers2

2

You can use another array function such as reduce like:

this.state.resp.reduce(function(list, e) {
   list[e.OriginLocation.AirportCode] = e.OriginLocation.CityName;
   return list;
}, {});

reduce will then return the accumulated list which you can use or return directly (without assigning it to a variable if you want).

ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
1

You can create an object inside the forEach:

whatever.forEach(function(e) {
   var list[e.OriginLocation.AirportCode] = e.OriginLocation.CityName; 
});

But you will lose the reference (named list) to your object when the forEach completes. References are stored on the call stack (which will be lost when the call to forEach returns) and the object itself is stored on the heap.

The object will still exist in memory, but you won't have a reference to it.

Useful reading:

http://cslibrary.stanford.edu/102/PointersAndMemory.pdf

What and where are the stack and heap?

How variables are allocated memory in Javascript?

andydavies
  • 3,081
  • 4
  • 29
  • 35