gpt4 book ai didi

javascript - 获取特定 id 上对象数组中的对象索引 - javascript 或 jQuery

转载 作者:行者123 更新时间:2023-11-30 15:27:59 24 4
gpt4 key购买 nike

我有以下对象数组:

[
{
"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 中完成?

最佳答案

使用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#findArray#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);

关于javascript - 获取特定 id 上对象数组中的对象索引 - javascript 或 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42678114/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com