user2157179
user2157179

Reputation: 236

Object not pushing correctly into array

I am trying to push an object in to an array in a jQuery $.each loop but when I try to push an object into an array it does not store correctly and it overwrites what was previously in the array.

The code looks like this:

var ing = {};
var mData = [];

$.post('find.php', {levels:levels}, function(res){
        var resData = $.parseJSON(res);
        if (resData.success == true){

            var mName = resData.m_name;
            var p = resData.p;
            $.each(p, function(key,val){

                ing.name = val.name;
                ing.weight = val.weight;
                ing.i_count = val.i_total;
                ing.l_count = val.l_total;
                //console.log(ing);
                mData.push(ing);
                //console.log(mData);
            });

        }
    });
 console.log(mData);

The ing variable shows the data I would expect every time in the loop however when the data gets pushed into the array the first index of the array gets overwritten by the second index, which results in something like this.

 { name="tea", weight="250", i_count=26, l_count = 1},{ name="tea", weight="250", i_count=26, l_count = 1}

So my question is what is wrong with the way I am pushing the data into the array?

Upvotes: 0

Views: 60

Answers (1)

suman j
suman j

Reputation: 6960

You declared ing variable outside the $.each method. this effectively overrides each time. Declare it inside the $.each loop code.

$.each(p, function(key,val){
  var ing = {}
   ...
   ... update ing variable

Upvotes: 2

Related Questions