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}
}
}
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}
}
}
Share
Improve this question
asked Nov 22, 2014 at 12:34
EgidiEgidi
1,7769 gold badges45 silver badges70 bronze badges
1
-
nope, because
{'id': valuetofind}
creates a new object literal which is distinct from every other object. (even if it wasn't, still it wouldn't equal the objects in the array because it lacks other keys.) – The Paramagnetic Croissant Commented Nov 22, 2014 at 12:39
3 Answers
Reset to default 5This 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;
}
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]
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);