首页 > 解决方案 > GREP 未检测到数组中添加的元素

问题描述

我从后端加载了一个包含 100 个元素的数组。

console.log(array)显示 100 个元素。

然后我通过 ajax 获得 1 个新元素并将其添加到数组中array.push(new_element);

console.log(array)显示 101 个元素。

如果我console.log(array[array.length-1])得到我添加的元素。

到目前为止一切正常,数据正确。这是从添加的元素中捕获的。

在此处输入图像描述


然后我想在列表中显示选定元素的子集。

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

添加的 101 元素被“选中”,确认,但我没有进入 sub_array。


我检查了所有逻辑,没关系。不明白为什么我没有得到 101 元素。

似乎 grep 命令从原始版本而不是更新版本获取数组数据。

就像它进入更深层次的记忆或类似的东西。那可能吗?

一些代码

// 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 项目示例

在此处输入图像描述

欢迎任何线索!谢谢。

标签: javascriptjquery

解决方案


ajaxrepsonse 中,data.extra_course它是一个数组而不是一个对象。
您将必须获取第一个元素extra_course并将其推送到array如下所示:

$.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) {
  },
});

推荐阅读