简体   繁体   中英

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. 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

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. 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.

  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.

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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