Reputation: 1776
I need search in an array of JSON objects if a key with especific id value exists. If exists, return it, if not return -1 or whatever
var array = [{'id': 1, 'name': 'xxx'},
{'id': 2, 'name': 'yyy'},
{'id': 3, 'name': 'zzz'}];
var searchValue --> id==1
should be something like this?
function search_array(array,valuetofind) {
if array.indexof({'id': valuetofind}) != -1 {
return array[array.indexof({'id': valuetofind})]
} else {
return {'id': -1}
}
}
Upvotes: 4
Views: 8980
Reputation: 101
try this
search(nameKey, myArray){
for (var i=0; i < myArray.length; i++) {
if (myArray[i].name === nameKey) {
return myArray[i];
}
}
}
var array = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
];
var resultObject = search("string 1", array);
Upvotes: 0
Reputation: 66
This returns the object if a match exists and -1 if there's no match.
function search_array(array,valuetofind) {
for (i = 0; i < array.length; i++) {
if (array[i]['id'] === valuetofind) {
return array[i];
}
}
return -1;
}
Upvotes: 5
Reputation: 796
If you simply need to make sure the id exists try this:
function search_array(array, valuetofind) {
var exists = false;
for(i=0;i<array.length;i++) {
if(array[i].id == valuetofind) {
exists = true;
}
}
return exists;
}
My method may be a little long winded cycling through each part but i checked and it works
search_array(array, 4) [False]
search_array(array, 1) [True]
Upvotes: 0