在未选择下拉列表时更改对象数组中的值

问题描述 投票:1回答:1

我想基于下拉菜单中的选择来更改对象数组中的值。

arr= [
        {name: 'one', in_order: true, other_key:'ga'},
        {name: 'one', in_order: true, other_key:'gb'},
        {name: 'one', in_order: true, other_key:'gc'},
        {name: 'two', in_order: false, other_key:'gd'},
        {name: 'two', in_order: false, other_key:'ge'},
        {name: 'two', in_order: false, other_key:'gf'},
        {name: 'three', in_order: false, other_key:'gg'},
        {name: 'three', in_order: false, other_key:'gh'},
        {name: 'three', in_order: false, other_key:'gi'},
        {name: 'four', in_order: false, other_key:'gj'},
        {name: 'four', in_order: false, other_key:'gk'},
        {name: 'four', in_order: false, other_key:'gl'}
     ]

我这样做:

$(`#filter`).on('change', function() {
   yo = [];
   $('option:selected', this).each(function() {
        yo.push(this.value);
   });

  arr.forEach(arr_opts => {
            yo.forEach(opt => {
                if (arr_opts.name == opt) {
                    arr_opts.in_order = true;
                }
            });
        });
        console.log(arr);
});

当我这样做时,我得到了结果。但是,当我在下拉列表中取消选择结果时,它不会变回false。例如,如果我检查onetwo。它将数组中的两个值都更改为true。但是,如果我然后取消选择two,则two仍为true

在取消选择时,可以将选择的值改回false吗?

这里是我的fiddle

javascript jquery arrays ecmascript-6 dropdown
1个回答
0
投票

我用$.inArray算出

arr= [
        {name: 'one', in_order: true, other_key:'ga'},
        {name: 'one', in_order: true, other_key:'gb'},
        {name: 'one', in_order: true, other_key:'gc'},
        {name: 'two', in_order: false, other_key:'gd'},
        {name: 'two', in_order: false, other_key:'ge'},
        {name: 'two', in_order: false, other_key:'gf'},
        {name: 'three', in_order: false, other_key:'gg'},
        {name: 'three', in_order: false, other_key:'gh'},
        {name: 'three', in_order: false, other_key:'gi'},
        {name: 'four', in_order: false, other_key:'gj'},
        {name: 'four', in_order: false, other_key:'gk'},
        {name: 'four', in_order: false, other_key:'gl'}
     ]
console.log(arr);

let yo;
$(`#filter`).on('change', function() {
   yo = [];
   $('option:selected', this).each(function() {
        yo.push(this.value);
   });
   
 console.log(yo);

  arr.forEach(arr_opts => {
 		if ($.inArray(arr_opts.name, yo) !== -1) {
    	arr_opts.in_order = true;
  	} else {
    	arr_opts.in_order = false;
    }
  });
  console.log(arr);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select id='filter' multiple>
  <option value='one' selected>one</option>
  <option value='two'>two</option>
  <option value='three'>three</option>
  <option value='four'>four</option>
</select>
© www.soinside.com 2019 - 2024. All rights reserved.