Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check if key exists in a list of key value array

I have a like that is like

[
   {Key: 'FName', Value: 'John'},
   {Key: 'LName', Value: 'Doe'},
   {Key: 'Age', Value: '30'},
   {Key: 'Person', Value: 'true'}
]

How is it possible to check if Person exists as a Key?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Solution 1

You can use <Array>.some

I also made the function take the key you are searching in and the value that you are seeking

const arr = [
   {Key: 'FName', Value: 'John'},
   {Key: 'LName', Value: 'Doe'},
   {Key: 'Age', Value: '30'},
   {Key: 'Person', Value: 'true'}
];




function isValueInsideField(arr, fieldName, value){
  return arr.some(e => e[fieldName] === value);
}

console.log(isValueInsideField(arr, 'Key', 'Person'))
console.log(isValueInsideField(arr, 'Key', '123'))

Solution 2

if you want to retrieve another value from the array

const arr = [
   {Key: 'FName', Value: 'John'},
   {Key: 'LName', Value: 'Doe', someKey:false},
   {Key: 'Age', Value: '30'},
   {Key: 'Person', Value: 'true'}
];




function retriveValueIfKeyExists(arr, keyFieldName, value, valueFieldName){
  // nullish concealing operator to return value even if it is falsy
  // you can change it with || operator  but this might lead to un wanted results
  // if the value is 0 or the boolean value false
  return arr.filter(e => e[keyFieldName] === value)[0]?.[valueFieldName] ?? null;
}

console.log(retriveValueIfKeyExists(arr, 'Key', 'Person', 'Value'))
console.log(retriveValueIfKeyExists(arr, 'Key', 'LName', 'someKey'))

console.log(retriveValueIfKeyExists(arr, 'Key', '123'))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading