简体   繁体   English

从jQuery数组中的数组中获取特定元素

[英]Get specific elements from arrays within array in jQuery

I am having some trouble with getting what I want out of jQuery. 我在从jQuery中获取所需内容时遇到了一些麻烦。 I have an ajax call that returns and array of arrays. 我有一个ajax调用,它返回和数组数组。

my jQuery looks something like this... 我的jQuery看起来像这样...

$.each(search_results, function()
{
  $.each(this, function(results)
  {
    var first_name = '';
    var last_name = '';
    $.each(this, function(index, value)
    {
      if(index == 3 )
      {
        last_name = value;
      }

      if(index == 5)
      {
        first_name = value;
        var contact_name = first_name + " " + last_name;
        var result_item = '<li class="list-group-item">' + contact_name + '</li>';
          $(id).append(result_item);
      }
    });
  });
});

This works and is all well and good, but I'm returning hundreds of records. 这项工作很好,而且很好,但是我要返回数百条记录。 Looping through each element in the array to pickout two to five elements seems like WAY too much work. 遍历数组中的每个元素以挑选2到5个元素似乎很麻烦。

Is there a way to do something like this... 有没有办法做这样的事情...

  $.each(search_results, function()
{
  $.each(this, function(results)
  {
    $.each(this, function(result)
    {
       var first_name = result[5];
       var last_name = result[3];
        var contact_name = first_name + " " + last_name;
        var result_item = '<li class="list-group-item">' + contact_name + '</li>';
          $(id).append(result_item);
      }
    });
  });
});

I found a similar question here , but the answer seems odd to me. 我在这里找到了类似的问题,但答案对我来说似乎很奇怪。 There has to be a way.... 必须有一种方法。

I hope this helps more 我希望这会有所帮助

Array / JSON Structure: 数组/ JSON结构:

Object { search_results: […] }
search_results : Array [ […], […], […], … ]
[0..99]
0 : Array [ "all", "stuff", "I want", … ]

From what I understood from your question, you have an array similar to: 根据您对问题的了解,您有一个类似于以下内容的数组:

 var search_results = [
                         [
                            [1.0, 1.1, 1.2, 1.3, 1.4, 1.5], 
                            [2.0, 2.1, 2.2, 2.3, 2.4, 2.5]
                         ]
                      ];

And you want to access elements 1.3, 1.5, 2.3, 2.5.... 您想访问元素1.3、1.5、2.3、2.5 ....

Following code will access those elements. 以下代码将访问这些元素。

$.each(search_results, function(l1_index, l1_result)
{
   $.each(this, function(l2_index, l2_result)
   {
     if(l2_result.length > 5)
     {
         var last_name = l2_result[3];
         var first_name = l2_result[5];
         var contact_name = first_name + " " + last_name;
         var result_item = '<li class="list-group-item">' + contact_name + '</li>';
         $(id).append(result_item);
     }
  });
});

PS: If you can post your array structure everyone can better understand your question. PS:如果您可以发布数组结构,那么每个人都可以更好地理解您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM