sirVir
sirVir

Reputation: 1516

forEach context when using loop to modify object literal

I'm trying to merge two arrays of objects into one which makes more sense in the application (google maps api v3). I'm getting obj2 is undefined error. As far as I understand it is connected to context - I'm calling a function inside forEach loop, and it does not have the access to the objects in the "upper" loop. How can I pass the context or redefine those loops to make it work? nodes and generation contain lists of objecs. Those objects are simple key-value sets.

database = new Array;
function processData(nodes,generation) {


  nodes.forEach(function(value)
  {
     var obj = {
     lat : value.Latitude,
     lng : value.Longitude,
     data : {ID: value.Node, 
            timentries : []}
     }

     currentDate = generation[0].datetime;
     var obj2 =
     {
        time: currentDate,
        technologies :[]
     }

     generation.forEach(function(value2)
     {
        if (value2.datetime == currentDate)
        {
           if (value2.node == obj.data.ID)
              {
                 var obj3 = {
                    type : value2.technology,
                    output : value2["output"],
                    emission : value2["emissions"]
                 }
                 obj2.technologies.push(obj3);
              }
        }
        else
        {
           timentries.push(obj2)
           currentDate = value2.datetime;
           delete obj2;
           var obj2 =
           {
              time: currentDate,
              technologies :[]
           }

        }
     })


  database.push(obj)   
  })
};
$( document ).ready(function() {
    loadData(processData);
});

the error occurs in the first reference to obj2:

 if (value2.datetime == currentDate)
        {
           if (value2.node == obj.data.ID)
              {
                 var obj3 = {
                    type : value2.technology,
                    output : value2["output"],
                    emission : value2["emissions"]
                 }
                 obj2.technologies.push(obj3);
              }
        }

Upvotes: 0

Views: 586

Answers (1)

zbateson
zbateson

Reputation: 1104

From the looks of it, your code is hitting this part:

    else
    {
       timentries.push(obj2)
       currentDate = value2.datetime;
       delete obj2;
       var obj2 =
       {
          time: currentDate,
          technologies :[]
       }

    }

Note that you're deleting obj2 and re-declaring obj2 in the local scope of the "else" block. There's no need to delete it (which actually wouldn't have an affect on a variable anyway) and re-declare it. Instead of those lines, just do:

    else
    {
       timentries.push(obj2)
       currentDate = value2.datetime;
       obj2 =
       {
          time: currentDate,
          technologies :[]
       };
    }

Upvotes: 1

Related Questions