Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript findIndex not working for first object

var data=[{"vpnkey":"CUSTOMER_NAME","validation":"ALPHANUMERIC"},
{"vpnkey":"VRF","validation":"VRF_CHECK"},
{"vpnkey":"MOBILE_ADDRESS_SUMMARIZED_RANGE","validation":"IP_MASK"},
{"vpnkey":"APN_MOBILE_RANGE","validation":"IP_MASK"},
{"vpnkey":"FIXED_IP_LOOPBACK_TRACK_ID","validation":"NUMERIC"},
{"vpnkey":"CUSTOMER_BGP_REMOTE_AS","validation":"NUMERIC"},
{"vpnkey":"testing_purpass1","validation":"IP_ADDRESS"},
{"vpnkey":"testing_purpass2","validation":"IP_ADDRESS"}]

when i search vpnkey With first object "vpnkey value" it is returning -1 but expected result 0

this.vpnKeys["Commonkeys"].findIndex(function(item, i){
   if(item.vpnkey === "CUSTOMER_NAME") return i
});

when i search based on vpnkey other then first object "vpnkey value" it gives proper index value

this.vpnKeys["Commonkeys"].findIndex(function(item, i){
   if(item.vpnkey === "VRF") return i
});
like image 404
Vinay urs Avatar asked Aug 09 '26 18:08

Vinay urs


1 Answers

findIndex will return the index of the first element in the array that satisfies the condition. So instead of returning i you can return item.vpnkey === "CUSTOMER_NAME"

var data = [{
  "vpnkey": "CUSTOMER_NAME",
  "validation": "ALPHANUMERIC"
}, {
  "vpnkey": "VRF",
  "validation": "VRF_CHECK"
}, {
  "vpnkey": "MOBILE_ADDRESS_SUMMARIZED_RANGE",
  "validation": "IP_MASK"
}, {
  "vpnkey": "APN_MOBILE_RANGE",
  "validation": "IP_MASK"
}, {
  "vpnkey": "FIXED_IP_LOOPBACK_TRACK_ID",
  "validation": "NUMERIC"
}, {
  "vpnkey": "CUSTOMER_BGP_REMOTE_AS",
  "validation": "NUMERIC"
}, {
  "vpnkey": "testing_purpass1",
  "validation": "IP_ADDRESS"
}, {
  "vpnkey": "testing_purpass2",
  "validation": "IP_ADDRESS"
}]



const x = data.findIndex(function(item, i) {
  return item.vpnkey === "CUSTOMER_NAME"
});
console.log(x)
like image 134
brk Avatar answered Aug 12 '26 07:08

brk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!