简体   繁体   English

如何通过比较 javascript 中的检查值来获取对象/数组的索引

[英]How to get the index of object/array by comparing its checked value in javascript

I have an array of object 'obj', whose values are populating into html as checkbox value.我有一个 object 'obj' 数组,其值作为复选框值填充到 html 中。 Now when I uncheck any checkbox, I need to get the index of array of object of which its belong to by comparing with the array of object 'obj'.For Ex- suppose I uncheck first 'createddate', then I should get index as 0 so on.. Here is the code below现在,当我取消选中任何复选框时,我需要通过与 object 'obj'的数组进行比较来获取其所属的 object 数组的索引。例如,假设我取消选中第一个 'createddate',那么我应该得到索引为0等等..这是下面的代码

html html

<div class="menu-outer-block">
    <div class="menu-block" id="menu-block">
      <div id="menu"></div>
    </div>
  </div>

script脚本

let Obj = /* this.guidelineObj;*/ [{
        mainitem: "My item 1",
        Seconditem: {
          createddate: "30-01-02",
          enddate: "30-01-03"
        }
      },
      {
        mainitem: "My item 2",
        Seconditem: {
          createddate: "30-01-02",
          enddate: "30-01-03"
        }
      }
    ];
    const lines1 = [];
    const columns = {};
    Obj.reverse().forEach(col => {
      lines1.push('<div>' + col.mainitem + '</div>');
      Object.keys(col.Seconditem).forEach(key => {
        columns[key] = true;
        const checked = columns[key] ? 'checked' : '';
        lines1.push(
          "<label><input  class='menu-checkbox' type='checkbox' name='" +
          key +
          `' ` +
          checked +
          '>' +
          key +
          '</label>'
        );
      });
    });
    document.getElementById("menu").innerHTML = lines1.join('<br>');
    const dropDown = document.querySelector('#menu');
    dropDown.setAttribute('style', 'display:block;');
    dropDown.addEventListener('change', e => {
      console.log(e)
    })

Since you are already creating the checkboxes dynamically you can simply add a data attribute holding the mainitem value of the object.由于您已经在动态创建复选框,您可以简单地添加一个数据属性来保存 object 的mainitem值。 It is then trivial to retrieve this from the event.target ( event.target.dataset.mainitem ) and use it to either find() the object in the array or findIndex() of the object in the array by comparing mainitem values.然后从event.target ( event.target.dataset.mainitem ) 中检索它并使用它通过比较mainitem值来find()数组中的 object 或数组中 object 的findIndex()是很简单的。

  const mainitem = e.target.dataset.mainitem;
  // find the object
  const o = Obj.find(o => o.mainitem === mainitem);
  // or find the index
  const oIndex = Obj.findIndex(o => o.mainitem === mainitem);

Note you are calling reverse() on your array before your loop, which mutates your array in place , so the results of findIndex() will be reversed from the original order.请注意,您在循环之前在数组上调用reverse() ,这会在原地改变数组,因此findIndex()的结果将与原始顺序相反。

 let Obj = [{ mainitem: "My item 2", id: 1, Seconditem: { createddate: "30-01-02", enddate: "30-01-03" } }, { mainitem: "My item 2", id: 2, Seconditem: { createddate: "30-01-02", enddate: "30-01-03" } }, { mainitem: "My item 2", id: 3, Seconditem: { createddate: "30-01-02", enddate: "30-01-03" } }]; const lines1 = []; const columns = {}; Obj.reverse().forEach(col => { lines1.push('<div>' + col.mainitem+ ' id: '+ col.id + '</div>'); Object.keys(col.Seconditem).forEach(key => { columns[key] = true; const checked = columns[key]? 'checked': ''; lines1.push( `<label> <input class='menu-checkbox' type='checkbox' name='${key}' data-id='${col.id}' ${checked} > ${key} </label>` ); }); }); document.getElementById("menu").innerHTML = lines1.join('<br>'); const dropDown = document.querySelector('#menu'); dropDown.setAttribute('style', 'display:block;'); dropDown.addEventListener('change', e => { const id = e.target.dataset.id; // find the object const o = Obj.find(o => o.id == id); // or find the index const oIndex = Obj.findIndex(o => o.id == id); console.log(oIndex, ' - ', o); })
 <div class="menu-outer-block"> <div class="menu-block" id="menu-block"> <div id="menu"></div> </div> </div>

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

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