Egi*_*idi 4 javascript arrays indexing json
如果存在具有特定 id 值的键,我需要在 JSON 对象数组中进行搜索。如果存在则返回,如果不存在则返回-1或者其他
var array = [{'id': 1, 'name': 'xxx'},
{'id': 2, 'name': 'yyy'},
{'id': 3, 'name': 'zzz'}];
var searchValue --> id==1
Run Code Online (Sandbox Code Playgroud)
应该是这样的吗?
function search_array(array,valuetofind) {
if array.indexof({'id': valuetofind}) != -1 {
return array[array.indexof({'id': valuetofind})]
} else {
return {'id': -1}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
如果存在匹配则返回该对象,如果不存在则返回-1。
function search_array(array,valuetofind) {
for (i = 0; i < array.length; i++) {
if (array[i]['id'] === valuetofind) {
return array[i];
}
}
return -1;
}
Run Code Online (Sandbox Code Playgroud)