检查对象的JavaScript数组中存在对象的值,如果没有一个新的对象添加到阵列 [英] Check if object value exists within a Javascript array of objects and if not add a new object to array
本文介绍了检查对象的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
,则意味着是唯一在这里。 <一href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/some\"><$c$c>some$c$c>对于检查的事物的存在数组中的一个伟大的功能:
I've assumed that id
s are meant to be unique here. some
is a great function for checking the existence of things in arrays:
function checkAndAdd(name) {
var id = arr.length + 1;
var found = arr.some(function (el) {
return el.username === name;
});
if (!found) { arr.push({ id: id, username: name }); }
}
这篇关于检查对象的JavaScript数组中存在对象的值,如果没有一个新的对象添加到阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文