如果存在具有特定id值的键,我需要在JSON对象数组中搜索。如果存在,返回它,如果没有返回-1或任何Javascript |搜索JSON数组中的特定键值
var array = [{'id': 1, 'name': 'xxx'},
{'id': 2, 'name': 'yyy'},
{'id': 3, 'name': 'zzz'}];
var searchValue --> id==1
应该是这样的?
function search_array(array,valuetofind) {
if array.indexof({'id': valuetofind}) != -1 {
return array[array.indexof({'id': valuetofind})]
} else {
return {'id': -1}
}
}
没了,因为'{ 'ID':valuetofind}'创建一个新对象字面是从每一个其他对象不同。 (即使不是这样,它仍然不等于数组中的对象,因为它缺少其他键)。 – 2014-11-22 12:39:19