reshad reshad - 25 days ago 7
Java Question

Check if a string is in a list or not (JavaScript)

I have a list as below:

var myList = [{type:'Prospect__c', typeName__c:'high_school', },
{type:'Procedure__c', typeName__c:'in_program', },
{type:'Procedure__c', typeName__c:'attention_plz', }]


I want to check if
in_program
(which is present in my list), exists in my list or not?
I've used different types of codes in order to get the result but I did not succeed.

Here are some of my tries:


if (myList.indexOf('in_program')>0)

if (myList.indexOf(typeName__c:'in_program')>0)

if (myList.indexOf(" typeName__c:'in_program' ")>0)

Answer

You can use following approach in different scenario:

JSON.stringify

If its just about finding availability, you can get JSON string and then check in it.

As correctly pointed by corn3lius, just checking search value will search in keys as well. You can wrap searchValue in ":..." and this will only search in values

var myList = [{type:'Prospect__c', typeName__c:'high_school', },
{type:'Procedure__c', typeName__c:'in_program', },
{type:'Procedure__c', typeName__c:'attention_plz', }]
var searchVal = 'in_program';

var exist= JSON.stringify(myList).indexOf(":\"" + searchVal + "\"") > -1;

console.log(exist)

Array.some

An alternate could be using array function if you know the exact key to lookup

var myList = [{type:'Prospect__c', typeName__c:'high_school', },
{type:'Procedure__c', typeName__c:'in_program', },
{type:'Procedure__c', typeName__c:'attention_plz', }]
var searchVal = 'in_program';

var exist= myList.some(function(o){ return o.typeName__c === searchVal });

console.log(exist)

Array.find

If you want to find first object where value matches, you should use Array.find

var myList = [{type:'Prospect__c', typeName__c:'high_school', },
{type:'Procedure__c', typeName__c:'in_program', },
{type:'Procedure__c', typeName__c:'attention_plz', }]
var searchVal = 'in_program';

var exist= myList.find(function(o){ return o.typeName__c === searchVal });

console.log(exist)

Array.filter

If you want to find all objects where value matches, you should use Array.filter

var myList = [{type:'Prospect__c', typeName__c:'high_school', },
{type:'Procedure__c', typeName__c:'in_program', },
{type:'Procedure__c', typeName__c:'attention_plz', }]
var searchVal = 'Procedure__c';

var exist= myList.filter(function(o){ return o.type === searchVal });

console.log(exist)

Comments