4

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}
 }
}
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.) Commented Nov 22, 2014 at 12:39

3 Answers 3

5

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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] 

1 Comment

From condition "If exists, return it,"
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.