PDA

View Full Version : How to check if an array contains a specific value?

BaronZ
10-09-2012, 03:59 AM
i have an array like below:
[{"A":"a","B":"b"},{"A":"a","B":"b"},{"C":"c"}]

how to check if the array elements' key contains "A"?(only key)

xelawho
10-09-2012, 04:10 AM
<script type="text/javascript">
var theArray=[{"A":"a","B":"b"},{"A":"a","B":"b"},{"C":"c"}]
for (var i = 0; i < theArray.length; i++) {
var pos=0;
for(b in theArray[i]){
if(b=="A"){
alert('"A" found in object '+i+' at position '+pos)
}
pos++
}
}
</script>

BaronZ
10-09-2012, 06:34 AM
<script type="text/javascript">
var theArray=[{"A":"a","B":"b"},{"A":"a","B":"b"},{"C":"c"}]
for (var i = 0; i < theArray.length; i++) {
var pos=0;
for(b in theArray[i]){
if(b=="A"){
alert('"A" found in object '+i+' at position '+pos)
}
pos++
}
}
</script>

what do u think of this one?

var arr = [{"A":"a","B":"b"},{"A":"a","B":"b"},{"C":"c"}] ;
for(var i=0;i<3;i++)
{
if(arr[i].A!=undefined)
}

Dormilich
10-09-2012, 12:38 PM
depending on the situation, the array iteration methods are also useful.

var has_A = arr.some(function (item) {
return ("A" in item);
});

10-09-2012, 01:31 PM
if("A" in theArray)

Dormilich
10-09-2012, 02:04 PM
if("A" in theArray)
looks cool, does it work?