Фильтрация элементов в массиве JavaScript с помощью jQuery

У меня есть массив JavaScript, который ниже, который мне нужно отфильтровать, чтобы получить правильные дочерние значения из приведенных ниже тестовых данных.

var arrChildOptions2 = [
        {Parent:'opt1',Value:'opt1',Text:'Parent1 - Child 1'}, 
        {Parent:'opt2',Value:'opt1',Text:'Parent 2 - Child 1'},
        {Parent:'opt2',Value:'opt2',Text:'Parent 2 - Child 2'}
    ];

Значения используются для заполнения раскрывающегося списка на основе события изменения родительского выпадающего списка, как показано ниже.

$(function() {
    $('#ddl1').change(function() {
        $('#ddl2 option:gt(0)').remove();
        $('#ddl2').addItems('#ddl2', arrChildOptions2[Parent=opt2]);
    });
});

где additems - это функция, проходящая через массив. Проблема в том, что я не могу заставить его фильтровать родителем, я пробовал использовать содержит и выше arrChildOptions2 [Parent = opt2], но я не могу получить его фильтр, я бы предпочел найти аккуратное решение, а не использовать цикл for? Любые идеи, приветствия

Ответы

Ответ 1

У вас может быть больше удачи, используя функцию jQuery.grep(), а не возиться с циклами.

Эта функция "Находит элементы массива, которые удовлетворяют функции фильтра. Исходный массив не влияет".

Ответ 2

Да, попробуйте jquery grep, например:

arr = jQuery.grep( JSON_ARRAY, index);

Ответ 3

array.filter() существует в ванильном JavaScript:

function isBigEnough(element) {
  return element >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]

Эта страница документации содержит polyfill для старых браузеров:

if (!Array.prototype.filter)
{
  Array.prototype.filter = function(fun /*, thisArg */)
  {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== "function")
      throw new TypeError();

    var res = [];
    var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
    for (var i = 0; i < len; i++)
    {
      if (i in t)
      {
        var val = t[i];

        // NOTE: Technically this should Object.defineProperty at
        //       the next index, as push can be affected by
        //       properties on Object.prototype and Array.prototype.
        //       But that method new, and collisions should be
        //       rare, so use the more-compatible alternative.
        if (fun.call(thisArg, val, i, t))
          res.push(val);
      }
    }

    return res;
  };
}

Ответ 4

Вы можете использовать jQuery.filter() для создания нового объекта jQuery из подмножества соответствующих элементов.

var result = [
        {Parent:'opt1',Value:'opt1',Text:'Parent1 - Child 1'}, 
        {Parent:'opt2',Value:'opt1',Text:'Parent 2 - Child 1'},
        {Parent:'opt2',Value:'opt2',Text:'Parent 2 - Child 2'}
    ];
    
        
var filteredResult = $(result).filter(function( idx ) {
    return result[idx].Parent === 'opt2';
});        
    
    
var options = $("#result-list");
$.each(filteredResult, function() {
    options.append($("<option />").val(this.Value).text(this.Text));
});    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<select id="result-list" name="select" title="List"/>