You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Username属性匹配修改JS数组中User对象的isAdmin属性

解决方案:匹配用户名并修改权限属性

嘿,我来帮你搞定这个需求!这里有个简洁又高效的实现方式,刚好能达到你想要的效果:

1. 先提取管理员用户名集合

先把数组1里所有的Username值提取出来,存入一个Set集合——因为Set的查找操作是O(1)的,比每次遍历数组查找要高效得多:

// 先定义你的两个数组
const array1 = [
  { Username: "admin", Enabled: true },
  { Username: "ftyjfj", Enabled: true },
  { Username: "ghjfgj", Enabled: true },
  { Username: "foo", Enabled: true }
];

const array2 = [
  { username: "foo", email: "foo@foo.com", enabled: true, status: "CONFIRMED", isAdmin: false },
  { username: "admin", email: "admin@foo.com", enabled: true, status: "CONFIRMED", isAdmin: false },
  { username: "sgrillon", email: "sgrillon@foo.com", enabled: true, status: "CONFIRMED", isAdmin: false },
  { username: "toto", email: "toto@foo.com", enabled: true, status: "CONFIRMED", isAdmin: false }
];

// 提取数组1的用户名到Set
const adminUsernameSet = new Set(array1.map(item => item.Username));

2. 遍历数组2修改权限

接下来遍历数组2的每个User对象,检查它的username是否在刚才的Set里,如果存在就把isAdmin设为true:

array2.forEach(user => {
  if (adminUsernameSet.has(user.username)) {
    user.isAdmin = true;
  }
});

效果验证

执行完上面的代码后,打印array2就能得到你想要的结果:

console.log(array2);
// 输出结果:
// [
//   { username: "foo", email: "foo@foo.com", enabled: true, status: "CONFIRMED", isAdmin: true },
//   { username: "admin", email: "admin@foo.com", enabled: true, status: "CONFIRMED", isAdmin: true },
//   { username: "sgrillon", email: "sgrillon@foo.com", enabled: true, status: "CONFIRMED", isAdmin: false },
//   { username: "toto", email: "toto@foo.com", enabled: true, status: "CONFIRMED", isAdmin: false }
// ]

为什么用Set?

如果直接用array1.some(item => item.Username === user.username)来判断,每次查找都要遍历整个数组1,时间复杂度是O(n*m)(n是数组1长度,m是数组2长度)。而用Set的话,查找是O(1),整体时间复杂度降到O(n+m),处理大量数据时性能提升很明显。

内容的提问来源于stack exchange,提问作者Stéphane GRILLON

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 03:44:40