JSON find in JavaScript
(You're not searching through "JSON", you're searching through an array -- the JSON string has already been deserialized into an object graph, in this case an array.)
Some options:
Use an Object Instead of an Array
If you're in control of the generation of this thing, does it have to be an array? Because if not, there's a much simpler way.
Say this is your original data:
[
{"id": "one", "pId": "foo1", "cId": "bar1"},
{"id": "two", "pId": "foo2", "cId": "bar2"},
{"id": "three", "pId": "foo3", "cId": "bar3"}
]
Could you do the following instead?
{
"one": {"pId": "foo1", "cId": "bar1"},
"two": {"pId": "foo2", "cId": "bar2"},
"three": {"pId": "foo3", "cId": "bar3"}
}
Then finding the relevant entry by ID is trivial:
id = "one"; // Or whatever
var entry = objJsonResp[id];
...as is updating it:
objJsonResp[id] = /* New value */;
...and removing it:
delete objJsonResp[id];
This takes advantage of the fact that in JavaScript, you can index into an object using a property name as a string -- and that string can be a literal, or it can come from a variable as with id
above.
Putting in an ID-to-Index Map
(Dumb idea, predates the above. Kept for historical reasons.)
It looks like you need this to be an array, in which case there isn't really a better way than searching through the array unless you want to put a map on it, which you could do if you have control of the generation of the object. E.g., say you have this originally:
[
{"id": "one", "pId": "foo1", "cId": "bar1"},
{"id": "two", "pId": "foo2", "cId": "bar2"},
{"id": "three", "pId": "foo3", "cId": "bar3"}
]
The generating code could provide an id-to-index map:
{
"index": {
"one": 0, "two": 1, "three": 2
},
"data": [
{"id": "one", "pId": "foo1", "cId": "bar1"},
{"id": "two", "pId": "foo2", "cId": "bar2"},
{"id": "three", "pId": "foo3", "cId": "bar3"}
]
}
Then getting an entry for the id in the variable id
is trivial:
var index = objJsonResp.index[id];
var obj = objJsonResp.data[index];
This takes advantage of the fact you can index into objects using property names.
Of course, if you do that, you have to update the map when you modify the array, which could become a maintenance problem.
But if you're not in control of the generation of the object, or updating the map of ids-to-indexes is too much code and/ora maintenance issue, then you'll have to do a brute force search.
Brute Force Search (corrected)
Somewhat OT (although you did ask if there was a better way :-) ), but your code for looping through an array is incorrect. Details here, but you can't use for..in
to loop through array indexes (or rather, if you do, you have to take special pains to do so); for..in
loops through the properties of an object, not the indexes of an array. Your best bet with a non-sparse array (and yours is non-sparse) is a standard old-fashioned loop:
var k;
for (k = 0; k < someArray.length; ++k) { /* ... */ }
or
var k;
for (k = someArray.length - 1; k >= 0; --k) { /* ... */ }
Whichever you prefer (the latter is not always faster in all implementations, which is counter-intuitive to me, but there we are). (With a sparse array, you might use for..in
but again taking special pains to avoid pitfalls; more in the article linked above.)
Using for..in
on an array seems to work in simple cases because arrays have properties for each of their indexes, and their only other default properties (length
and their methods) are marked as non-enumerable. But it breaks as soon as you set (or a framework sets) any other properties on the array object (which is perfectly valid; arrays are just objects with a bit of special handling around the length
property).
I had come across this issue for a complex model with several nested objects. A good example of what I was looking at doing would be this: Lets say you have a polaroid of yourself. And that picture is then put into a trunk of a car. The car is inside of a large crate. The crate is in the hold of a large ship with many other crates. I had to search the hold, look in the crates, check the trunk, and then look for an existing picture of me.
I could not find any good solutions online to use, and using .filter()
only works on arrays. Most solutions suggested just checking to see if model["yourpicture"]
existed. This was very undesirable because, from the example, that would only search the hold of the ship and I needed a way to get them from farther down the rabbit hole.
This is the recursive solution I made. In comments, I confirmed from T.J. Crowder that a recursive version would be required. I thought I would share it in case anyone came across a similar complex situation.
function ContainsKeyValue( obj, key, value ){
if( obj[key] === value ) return true;
for( all in obj )
{
if( obj[all] != null && obj[all][key] === value ){
return true;
}
if( typeof obj[all] == "object" && obj[all]!= null ){
var found = ContainsKeyValue( obj[all], key, value );
if( found == true ) return true;
}
}
return false;
}
This will start from a given object inside of the graph, and recurse down any objects found. I use it like this:
var liveData = [];
for( var items in viewmodel.Crates )
{
if( ContainsKeyValue( viewmodel.Crates[items], "PictureId", 6 ) === true )
{
liveData.push( viewmodel.Crates[items] );
}
}
Which will produce an array of the Crates which contained my picture.