简体   繁体   中英

Check value exists before pushing into a key-value array

I have a KendoUI grid with a checkbox column. I am getting checked row values into an array.

var list = new Array();
$("#values").data("kendoGrid").tbody.find("input").each(function(idx, item) {
  if (item.checked) {
    list.push({
      "Key": gridData[idx].id,
      "Value": gridData[idx].value
    });
  }
});

Before toApproveTransactions.push , I want to check if the value exists in list . How can I do this?

You can use the array.find function to do this.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

if (item.checked) {
    function valueExist = (element){
        return element.value == gridData[idx].value
    }


    if (!list.find(valueExist) ){
        list.push({
          "Key": gridData[idx].id,
          "Value": gridData[idx].value
        });
    }
  }

如果要检查list是否存在value ,可以执行以下操作:

list.map(obj => obj.Value).indexOf(value) >= 0;

You might want to consider making key as the index of the associative array like in the following code and check whether that key exists in the array. If it does just output duplicate. This might answer your question

 key = 'Key'; value = 'Value'; mArray = []; if(typeof(mArray[key])!=undefined) mArray[key] = value; else console.log('duplicate'); 

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