我有以下对象数组:
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna@melissa.tv"
"phone": "010-692-6593 x09125",
"website": "anastasia.net"
},...];
我传递id为2.我想要id = 2的对象数组的索引。 如何在javascript或jQuery中完成?
答案 0 :(得分:2)
使用Array#forEach
函数迭代obj,如果实际索引与参数中的给定id
相同,则将其分配到objId
变量。
如果没有给定id
的任何对象 - 函数将记录-1
。
let obj = [{id:1,name:"Leanne Graham",username:"Bret",email:"Sincere@april.biz",phone:"1-770-736-8031 x56442",website:"hildegard.org"},{id:2,name:"Ervin Howell",username:"Antonette",email:"Shanna@melissa.tv",phone:"010-692-6593 x09125",website:"anastasia.net"}];
function checkId(obj, id) {
let objId = -1;
obj.forEach((v,i) => v.id == id ? objId = i : v);
console.log(objId);
}
checkId(obj, 2);
checkId(obj, 4);
另一种方法,使用Array#find
和Array#indexOf
。
let obj = [{id:1,name:"Leanne Graham",username:"Bret",email:"Sincere@april.biz",phone:"1-770-736-8031 x56442",website:"hildegard.org"},{id:2,name:"Ervin Howell",username:"Antonette",email:"Shanna@melissa.tv",phone:"010-692-6593 x09125",website:"anastasia.net"}];
function checkId(obj, id) {
let objId = obj.indexOf(obj.find((v,i) => v.id == id)) || -1;
console.log(objId);
}
checkId(obj, 2);
checkId(obj, 4);
答案 1 :(得分:0)
您可以使用每个功能来完成:
var json = [
{"id":"1","tagName":"apple"},
{"id":"2","tagName":"orange"},
{"id":"3","tagName":"banana"},
{"id":"4","tagName":"watermelon"},
{"id":"5","tagName":"pineapple"}
];
$.each(json, function(idx, obj) {
if(obj.id == 2){
alert(idx);//will alert index where id = 2
}
});
有关详细信息,请访问:https://www.mkyong.com/jquery/jquery-loop-over-json-string-each-example/
答案 2 :(得分:0)
如果有一个或多个匹配项,此函数将返回索引数组:
function getIDs(obj,id) {
var ret = [];
obj.forEach((val,i) => val.id == id ? ret.push(i) : val);
return(ret);
}
var ids = getIDs(object,2);
console.log(ids);