Francisco Ghelfi
Francisco Ghelfi

Reputation: 962

GREP not detecting added elements in array

I have an array initialy loaded from the backend with 100 elements.

console.log(array) shows 100 elements.

Then I get 1 new element via ajax and add it to the array with array.push(new_element);

console.log(array) shows 101 elements.

If I console.log(array[array.length-1]) I get the element I added.

Everything fine so far and data is correct. This is a capture from the added element.

enter image description here


Then I want to show a subset of the selected elements in a list.

sub_array = jQuery.grep(array, function(n) { return ( n.selected === 'True' });

The added 101 element is "selected", confirmed, but I don't get in the sub_array.


I checked all the logic and it's ok. Can't understand why I don't get the 101 element.

It seems like if the grep command get's the array data from the original version and not the updated one.

Like if it goes to a deeper level of memory or something like that. Is that possible?

Some code

// Part 1 - The original data comes from Django backend

$(document).ready(function(){
    window.array = {{ course_list|safe }};
};


// Part 2 - Adding extra value

$.ajax({
    url:'/myurl',
    contentType : "application/json",
    dataType: 'json',

    success:function(data){

        console.log(array);
        // Here I get the correct number of 100 elements

        new_course = JSON.parse(data.extra_course);
        array.push(new_course);

        console.log(array);
        // Here I get the correct number of 101 elements
    },

    error:function(data){
    },
});

// Part 3 - 

function create_agenda() {
    console.log(array[array.length-1]);
    // Here I get the added element correctly

    sub_array = jQuery.grep(array, function(n) { return ( n.selected === 'True') });
    // Here I don't get the element. Even filtering by other fields
};

sub_array item example

enter image description here

Any clue welcome!! Thanks.

Upvotes: 1

Views: 52

Answers (1)

V. Sambor
V. Sambor

Reputation: 13369

Inside the ajax repsonse the data.extra_course comes as an array not an object.
You will have to get the first element of extra_course and push it to the array like this:

$.ajax({
  url: '/myurl',
  contentType: "application/json",
  dataType: 'json',

  success: function (data) {

    console.log(array);
    // Here I get the correct number of 100 elements

    new_course = JSON.parse(data.extra_course);  // THIS RETURNS AN ARRAY

    array.push(new_course[0]);  // < ------------- USE THE FIRST OBJECT HERE

    console.log(array);
    // Here I get the correct number of 101 elements
  },

  error: function (data) {
  },
});

Upvotes: 1

Related Questions