1

Possible Duplicate:
I have a nested data structure / JSON, how can I access a specific value?

I have a JSON that represents a list of bird species. Each bird is an object in the JSON. Within each object there are fields that represent locations. The locations are coded alphanumerically like ['P1UBA', 'P1UBC', etc]. A value of 1 in these fields represents presence while a 0 represents absence.

The code below shows one of these objects (there are 150 in the entire JSON).

[
    {
    "Species": "AMAV",
    "Common Name": "AMERICAN AVOCET",
    "Order": "Shorebirds",
    "Family": "Avocets",
    "P1UBA": "0",
    "P1UBC": "1",
    "P1UBF": "0",
    "P1UBG": "0",
    "P1ABA": "0",
    "P1ABC": "0",
    "P1ABF": "1",
    "P1ABFb": "0",
    "P1ABG": "0",
    "P1USA": "0",
    "P1USC": "0",
    }
]

How could I search through this object and return location fields==1? Ideally I would create a new array which is a string of those fields==1

Using the object above this would result in a new string of

var birdsMatch=['P1UBC','P1ABF']

I'd like to use jquery but am open to a pure javascript solution if it is more efficient

Community
  • 1
  • 1
jotamon
  • 1,532
  • 5
  • 18
  • 38

4 Answers4

1

Given that each bird object is in an Array named Birds the below will work.

$(data.Birds).each(function(index, element){
    if(element.value == '1')
        alert("FOUND BIRDS IN " + element.name);
})
abc123
  • 17,855
  • 7
  • 52
  • 82
1
var attr, result_arr = [];

for (attr in birdObj){
    if (birdObj[attr] === "1"){
        result_arr.push(attr);
    }
}

Where birdObj is similar to the obj example you give above.

Evan
  • 5,975
  • 8
  • 34
  • 63
1

You have to loop through all birds, then though all properties of each bird to collect the locations (assuming var birds contains your parsed JSON):

var birdsMatch = {};
for(var i=0; i<birds.length; i++) {
    // Create an empty array to keep locations found for each species
    birdsMatch[birds[i].Species] = []; 
    for(var loc in birds[i]) {
        if(birds[i][loc] === 1) {
            // Found! Add location to the correct species array
            birdsMatch[birds[i].Species].push(loc);
        }
    }
}

At the end, the birdsMatch object will look like this:

{
    AMAV : ['P1UBC','P1ABF'],
    OTHER_SPECIES : [], // not found in any locations
    YET_ANOTHER : ['LOC1']
    // ...
}
bfavaretto
  • 71,580
  • 16
  • 111
  • 150
  • Although I'm giving you a complete answer, I highly recommend reading the post Felix Kling suggested as a duplicate, to get a better understanding of how traversing js objects work. Your question will probably be closed as a dupe of that - however this time I'm not voting to close as such, as I believe that's too generic for your question. – bfavaretto Jan 23 '13 at 19:54
1

Using jQuery.map :

var birds = $.map(birdObj, function(value, key) { 
  return value === '1' ? key : null; 
});

//birds => ["P1UBC", "P1ABF"]
nekman
  • 1,919
  • 2
  • 15
  • 26