Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript | Search in an array of JSON by JSONs specific key value

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}
 }
}
like image 895
Egidi Avatar asked Nov 03 '25 13:11

Egidi


1 Answers

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;
}
like image 62
Mohamed El Alouani Avatar answered Nov 05 '25 07:11

Mohamed El Alouani