Saket Jain
Saket Jain

Reputation: 1382

How to copy an array of JSON objects in javascript

I have an array of objects in JavaScript. e.g. current_films[0].f_name, current_films[0].f_pattern etc. I want to copy the array into another similiar to the following:

for(var i=0; i<current_films.length; i++)
    {
            if(current_films[i].f_material == Value)
                {
                    temp[i] = current_films[i];
                }
    }

However, there seems to be an inexplicable problem when I do this. By inexplicable problem, I mean that the code does not execute and the array is not copied as I desire.

Any help would be greatly appreciated. Thank you!

P.S. Could you please mention why the above code would not work? As in, if I put an alert("Reached here");, it's not getting executed. Any ideas why its so?

Upvotes: 0

Views: 1718

Answers (2)

Paolo
Paolo

Reputation: 15827

P.S. Could you please mention why the above code would not work? As in, if I put an alert("Reached here");, it's not getting executed. Any ideas why its so?

I'd guess f_material is not defined for every element in the array.

If that's the case I'd use

if(typeof(current_films[i].f_material)!=='undefined')
{
    if(current_films[i].f_material == Value)
    {
        temp[i] = current_films[i];
    }
}

Anyway I'd suggest you to get familiar with the browser's javascript debugger (assumed that code runs in a browser)

Finally note that you're not copying the array/object:

temp[i] is a reference to current_films[i]

Modifying current_films later in the code will result in modifying temp

If that's not the behaviour desired Google for "javascript object copy".

Upvotes: 0

nkron
nkron

Reputation: 19791

One problem I see is that you set temp[i] to the value which means there would be gaps in the temp array. You could use push() to append the value to temp so you don't need to manage two sets of indices.

You could also use JavaScript's Array.filter() to do this a little easier. Filter will return a new array of the values from the original array where your function returns true.

var temp = current_films.filter(function(film) {
  return (film.f_material === Value);
});

Upvotes: 2

Related Questions