Domanda

I have a function which should built an array with keys. Those keys will have a serie of objects as value.

I've some loops nested in each other and I'm quite near to the solution, but inside the last loop I'm making a mistake and I can't see the solution.

The function loopt over an array with Id's. Those will be the key value for the output array. After that it loops over an array with a lot of objects. Those objects are having a property 'category'. Some of them have one, others more. So with a for-loop I loop over all the categories.

If the categorie is the same as the id then it should push the object to the var objs, which will be added to the right key.

This is all working, BUT, I want that the objects are saved with only ONE category. So I declared a new var inside the last loop, put the obj inside there and set the obj.category. Unfortunately this is overwriting the 'source', array[x].category. This is not good because this occurs the problem that an object with two categories will only be found once in this function and it had to be found twice so it can be saved twice (once by every represent key value).

A lot of explanation for a little piece of code...

$.each(unique_id, function(i, el){
    var objs = [];

    for(var x in array)
    {   
        for(var j=0; j<array[x].category.length; j++)
        {
            if(array[x].category[j] == el)
            {
                var obj = array[x];
                obj.category = el;
                objs.push(obj);
            }
        }
    }
    data[el] = objs;
})
È stato utile?

Soluzione

What is happening is : both obj and array[x] are pointing to same object. they are two references that point to same object .Can you try below:

     $.each(unique_id, function(i, el){
             var objs = [];

            for(var x in array)
            {   
               for(var j=0; j<array[x].category.length; j++)
               {
                   if(array[x].category[j] == el)
                   {
                      var obj = {};
                      $.extend(true,obj,array[x]);
                      obj.category = el;
                      objs.push(obj);
                   }
               }
            }
            data[el] = objs;
     });

Also, in javascript variables are function-scoped so even if you declare them inside the inner loop they are visible throughout the function and not only in the inner loop in which you have defined it. Of course $extend will copy every property that exists on array[x] and the nested objects and their properties as well. if you don't want that. just use

       var obj = {};
       obj.category = array[x].category;

provided category is also not object.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top