首页 文章资讯内容详情

从对象数组中检索用户ID-JavaScript

2026-06-04 1 花语

假设我们有一个对象数组,其中用户名映射到一些唯一的ID,例如:

const arr = [ {"4": "Rahul"}, {"7": "Vikram"}, {"6": "Rahul"}, {"3": "Aakash"}, {"5": "Vikram"} ];

从数组中可以明显看出,相同的名称可以具有多个ID,但是相同的ID可用于映射两个不同的名称。

我们需要编写一个JavaScript函数,该函数采用一个数组作为第一个参数,并使用名称字符串作为第二个参数。该函数应返回一个包含所有ID的数组,这些ID用于映射作为第二个参数提供的名称。

示例

以下是代码-

const arr = [ {"4": "Rahul"}, {"7": "Vikram"}, {"6": "Rahul"}, {"3": "Aakash"}, {"5": "Vikram"} ]; const name = Vikram; const findUserId = (arr, name) => { const res = []; for(let i = 0; i < arr.length; i++){ const key = Object.keys(arr[i])[0]; if(arr[i][key] !== name){ continue; }; res.push(key); }; return res; }; console.log(findUserId(arr, name));

输出结果

这将在控制台中产生以下输出-

[7, 5]