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)
alert('found A');
}
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);
});
Dormilich
10-09-2012, 02:04 PM
if("A" in theArray)
looks cool, does it work?
WolfShade
10-09-2012, 02:12 PM
It works, for me. I believe as long as it's an associative array, it will work for the key, not the value, I think.
Dormilich
10-09-2012, 02:23 PM
you are aware that there is no such thing as an "Associative Array" in JavaScript? (that would rather be an Object, lacking all Array methods).
and though "A" in obj works for objects/associative arrays, it does not for the OP’s variable, which is an Array of Objects, i.e. a nested structure.