Egidi
Egidi

Reputation: 1776

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}
 }
}

Upvotes: 4

Views: 8980

Answers (3)

Anish M Prasad
Anish M Prasad

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

Mohamed El Alouani
Mohamed El Alouani

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

MJPinfield
MJPinfield

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

Related Questions