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

I need search in an array of JSON objects if a key with especific id value exists. If exists, return it

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
Add a ment  | 

3 Answers 3

Reset to default 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;
}

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742421009a4440678.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信