Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way of basically doing a `where` clause in Javascript?

I'm trying to parse some JSON that is sent to me and it's all in the format of

[{key:value},{key2:value2}, ... ]

What would be the best way to get the value of key2 in this? Is there a way to do it without doing a for loop?

like image 584
Earlz Avatar asked Aug 05 '11 16:08

Earlz


2 Answers

Javascript Array comes with methods that do just what you are asking for - find entries without you having to code a for-loop.

You provide them with the condition that you want. A compact and convenient way to do that is with an arrow (or "lambda") function. In your case, you are looking for array entries that have a specific key, so the arrow function could look something like this:

e => e.hasOwnProperty("key2")

Following the lead of some of the others, let's start with the assumption

var arr = [{key:"value"}, {key2:"value2"}, {key3:"value3"}]

If you expect that at most one member of the array has the key you want, you can use the find() function. It will test each array member until it finds one where your condition is true, and return it. If none are true, you'll get undefined.

var foundentry = arr.find(e => e.hasOwnProperty("key2"))

Either foundentry will be undefined or it will be the {key2:"value2"} that you are looking for, and can extract value2 from it.


If arr can have more than one entry with the key that you are looking for, then instead of find() use filter(). It gives back an array of entries that meet your criteria.

var foundarray = arr.filter(e => e.hasOwnProperty("key2"))
like image 151
Dan K Avatar answered Sep 28 '22 16:09

Dan K


Not really, but it wouldn't be hard to create a function to do that. However, it would indeed involves a for loop.

For the sake of completion, that would be the function:

function selectWhere(data, propertyName) {
    for (var i = 0; i < data.length; i++) {
        if (data[i][propertyName] !== null) return data[i][propertyName];
    }
    return null;
}

Usage:

var key2value = selectWhere(data, "key2");
like image 43
laurent Avatar answered Sep 28 '22 16:09

laurent