检查对象值是否存在于 Javascript 对象数组中,如果不存在,则将新对象添加到数组中 [英] Check if object value exists within a Javascript array of objects and if not add a new object to array

查看:30
本文介绍了检查对象值是否存在于 Javascript 对象数组中,如果不存在,则将新对象添加到数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下对象数组:

If I have the following array of objects:

[ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]

有没有办法循环遍历数组来检查特定的用户名值是否已经存在,如果它什么都不做,但如果它不使用所述用户名(和新 ID)向数组中添加一个新对象?

Is there a way to loop through the array to check whether a particular username value already exists and if it does do nothing, but if it doesn't to add a new object to the array with said username (and new ID)?

谢谢!

推荐答案

我已经假设 id 在这里是唯一的.some 是用于检查数组中事物是否存在的一个很好的函数:

I've assumed that ids are meant to be unique here. some is a great function for checking the existence of things in arrays:

const arr = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }];

function add(arr, name) {
  const { length } = arr;
  const id = length + 1;
  const found = arr.some(el => el.username === name);
  if (!found) arr.push({ id, username: name });
  return arr;
}

console.log(add(arr, 'ted'));

这篇关于检查对象值是否存在于 Javascript 对象数组中,如果不存在,则将新对象添加到数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆