Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search an associate array / hash in Javascript [duplicate]

I have an array that looks like this

var data = [
 {"target": "production", "datapoints": [[165.0, 136], [141.0, 176], [null, 176]]},
 {"target": "test", "datapoints": [[169.0, 100], [151.0, 160], [null, 120]]},
 {"target": "backup", "datapoints": [[1.0, 130], [32.0, 120], [13.0, 130]]}
]

Is it possible to search this array to return the hash that contains for example "production"

{"target": "production", "datapoints": [[165.0, 136], [141.0, 176], [null, 176]]}

I looked at this http://api.jquery.com/jQuery.inArray/ but didn't know how to use it.


2 Answers

You can do:

var target = "production";
var result = $.grep(data, function(e){ return e.target == target; });

console.log(result);
like image 107
putvande Avatar answered Apr 18 '26 13:04

putvande


Not sure if this is what you meant, but try this:

for(var i=0;i<data.length;i++) 
    if(data[i].target=='production') 
        return data[i]
        // or do something else/more

This will iterate over the array and check the 'target' attribute for the value 'production'

like image 21
d'alar'cop Avatar answered Apr 18 '26 13:04

d'alar'cop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!