如果我有以下对象数组:
[ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
有没有办法循环遍历数组以检查特定的用户名值是否已经存在以及它是否确实无效,但是它是否没有使用所述用户名向新数组添加新对象(和新的ID)?
谢谢!
答案 0 :(得分:159)
我认为id
在这里是独一无二的。 some
是检查数组中事物存在的一个很好的函数:
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'));

答案 1 :(得分:19)
检查现有用户名是否相当简单:
var arr = [{ id: 1, username: 'fred' },
{ id: 2, username: 'bill'},
{ id: 3, username: 'ted' }];
function userExists(username) {
return arr.some(function(el) {
return el.username === username;
});
}
console.log(userExists('fred')); // true
console.log(userExists('bred')); // false
但是,当您必须向此阵列添加新用户时,该怎么做并不是那么明显。最简单的方法 - 只需推送id
等于array.length + 1
的新元素:
function addUser(username) {
if (userExists(username)) {
return false;
}
arr.push({ id: arr.length + 1, username: username });
return true;
}
addUser('fred'); // false
addUser('bred'); // true, user `bred` added
它将保证ID唯一性,但是如果某些元素将被取消,这将使该数组看起来有点奇怪。
答案 2 :(得分:8)
这个小小的片段对我有用..
const arrayOfObject = [{ id: 1, name: 'john' }, {id: 2, name: 'max'}];
const checkUsername = obj => obj.name === 'max';
console.log(arrayOfObject.some(checkUsername))
答案 3 :(得分:6)
最佳实践就是这样。
access_toke
答案 4 :(得分:2)
我认为,这是解决这个问题的最短途径。这里我使用了带有.filter的ES6箭头功能来检查是否存在新添加的用户名。
var arr = [{
id: 1,
username: 'fred'
}, {
id: 2,
username: 'bill'
}, {
id: 3,
username: 'ted'
}];
function add(name) {
var id = arr.length + 1;
if (arr.filter(item=> item.username == name).length == 0){
arr.push({ id: id, username: name });
}
}
add('ted');
console.log(arr);
答案 5 :(得分:2)
可能有多种可能的方式来检查元素( 您的案例(其对象)是否存在于数组中。
const arr = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }];
假设您要查找id = 3的对象。
1。找到: 它在数组中搜索元素,如果找到,则返回该元素,否则返回未定义。它返回提供的数组中满足提供的测试功能的第一个元素的值。 reference
const ObjIdToFind = 5;
const isObjectPresent = arr.find((o) => o.id === ObjIdToFind);
if (!isObjectPresent) { // As find return object else undefined
arr.push({ id: arr.length + 1, username: 'Lorem ipsum' });
}
2。过滤器: 它在数组中搜索元素,并过滤出所有符合条件的元素。它返回具有所有元素的新数组,如果没有元素与条件匹配,则返回一个空数组。 reference
const ObjIdToFind = 5;
const arrayWithFilterObjects= arr.filter((o) => o.id === ObjIdToFind);
if (!arrayWithFilterObjects.length) { // As filter return new array
arr.push({ id: arr.length + 1, username: 'Lorem ipsum' });
}
3。一些: some()方法测试数组中是否存在至少一个元素,该元素通过通过提供的函数实现的测试。它返回一个布尔值。 reference
const ObjIdToFind = 5;
const isElementPresent = arr.some((o) => o.id === ObjIdToFind);
if (!isElementPresent) { // As some return Boolean value
arr.push({ id: arr.length + 1, username: 'Lorem ipsum' });
}
答案 6 :(得分:2)
这是使用.map()
和.includes()
的ES6方法链:
const arr = [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
const checkForUser = (newUsername) => {
arr.map(user => {
return user.username
}).includes(newUsername)
}
if (!checkForUser('fred')){
// add fred
}
答案 7 :(得分:2)
假设我们有一个对象数组,并且您想检查name的值是否定义为这样,
let persons = [ {"name" : "test1"},{"name": "test2"}];
if(persons.some(person => person.name == 'test1')) {
... here your code in case person.name is defined and available
}
答案 8 :(得分:2)
尝试
使用某些方法的第一种方法
let arr = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }];
let found = arr.some(ele => ele.username === 'bill');
console.log(found)
第二种方法,使用包含地图
let arr = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }];
let mapped = arr.map(ele => ele.username);
let found = mapped.includes('bill');
console.log(found)
答案 9 :(得分:1)
我喜欢Andy的回答,但id并不一定是唯一的,所以这就是我想出来创建一个独特的ID。也可以在jsfiddle查看。请注意,如果以前删除了任何内容,arr.length + 1
可能无法保证唯一ID。
var array = [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' } ];
var usedname = 'bill';
var newname = 'sam';
// don't add used name
console.log('before usedname: ' + JSON.stringify(array));
tryAdd(usedname, array);
console.log('before newname: ' + JSON.stringify(array));
tryAdd(newname, array);
console.log('after newname: ' + JSON.stringify(array));
function tryAdd(name, array) {
var found = false;
var i = 0;
var maxId = 1;
for (i in array) {
// Check max id
if (maxId <= array[i].id)
maxId = array[i].id + 1;
// Don't need to add if we find it
if (array[i].username === name)
found = true;
}
if (!found)
array[++i] = { id: maxId, username: name };
}
答案 10 :(得分:1)
出于某些原因我确实尝试了上述步骤,但它似乎无法为我工作,但这是我对自己的问题的最终解决方案,可能对阅读此书的任何人都有用:
let pst = post.likes.some( (like) => { //console.log(like.user, req.user.id);
if(like.user.toString() === req.user.id.toString()){
return true
} } )
这里的post.likes是喜欢该帖子的一系列用户。
答案 11 :(得分:0)
这可以通过几个数组方法和几种不同的方式来相当简单地完成。
true
,或使用 .push()
时的数组长度)下面,我首先将数组映射到一个仅包含用户名的新浅层数组,然后检查该数组是否 .includes()
是指定的用户名。如果是,我会根据 true
运算符的性质返回 ||
。否则,我会将指定用户名的新对象推送回对象的源数组。
const arr = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }];
const usernameCheck = (arr, usr) => arr.map(u => u.username).includes(usr) || arr.push({ id: arr.length+1, username: usr });
usernameCheck(arr, 'jeremy');
console.log(arr);
true
或使用 .push()
时数组的长度:如果您想要更大的灵活性,这也可以通过多种方式进行改进。如果您不想返回 true
而是希望返回新数组以供立即使用,我们可以通过简单地在函数末尾返回数组来使用 ,
运算符,无论是没有推动。有了这个方案,仍然是push到原始数组,因为我们返回了数组,所以我们可以直接在函数执行上执行我们的console.log()
,而不需要先运行函数,然后记录数组的内容。
const arr = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }];
const usernameCheck = (arr, usr) => (arr.map(u => u.username).includes(usr) || arr.push({ id: arr.length+1, username: usr }), arr);
console.log(usernameCheck(arr, 'jeremy'));
另一方面,如果您只想返回新数组的浅拷贝而不直接推送到源数组,则可以使用扩展运算符 ...
或 .concat()
方法,如果你喜欢:
const arr = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }];
const usernameCheck = (arr, usr) => arr.map(u => u.username).includes(usr) ? [...arr] : [...arr, { id: arr.length+1, username: usr }];
console.log('This will return the array with the added username:\n\nusernameCheck(arr, \'jeremy\')', usernameCheck(arr, 'jeremy'));
console.log('But the original array remains untouched:\n\narr', arr);
答案 12 :(得分:0)
const checkIfElementExists = itemFromArray => itemFromArray 。 sameKey === outsideObject >。 samekey ;
if (cartArray.some(checkIfElementExists)) {
console.log('already exists');
} else {
alert('does not exists here')
答案 13 :(得分:0)
您也可以尝试
const addUser = (name) => {
if (arr.filter(a => a.name == name).length <= 0)
arr.push({
id: arr.length + 1,
name: name
})
}
addUser('Fred')
答案 14 :(得分:0)
这是我在@sagar-gavhane的回答之外所做的
const newUser = {_id: 4, name: 'Adam'}
const users = [{_id: 1, name: 'Fred'}, {_id: 2, name: 'Ted'}, {_id: 3, 'Bill'}]
const userExists = users.some(user => user.name = newUser.name);
if(userExists) {
return new Error({error:'User exists'})
}
users.push(newUser)
答案 15 :(得分:0)
函数number_present_or_not()
{
var arr = [ 2,5,9,67,78,8,454,4,6,79,64,688 ] ;
发现var = 6;
var found_two;
对于(i = 0; i
}
if ( found_two == found )
{
console.log("number present in the array");
}
else
{
console.log("number not present in the array");
}
}
答案 16 :(得分:0)
答案 17 :(得分:0)
xorWith
可用于实现这一目标
let objects = [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
let existingObject = { id: 1, username: 'fred' };
let newObject = { id: 1729, username: 'Ramanujan' }
_.xorWith(objects, [existingObject], _.isEqual)
// returns [ { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
_.xorWith(objects, [newObject], _.isEqual)
// returns [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ,{ id: 1729, username: 'Ramanujan' } ]
答案 18 :(得分:0)
也可以使用.some上的箭头功能,按照以下方式编写接受的答案
function checkAndAdd(name) {
var id = arr.length + 1;
var found = arr.some((el) => {
return el.username === name;
});
if (!found) { arr.push({ id: id, username: name }); }
}
答案 19 :(得分:0)
数组的本机函数有时比普通循环慢3到5倍。加上本机功能在所有浏览器中都不起作用,因此存在兼容性问题。
我的代码:
<script>
var obj = [];
function checkName(name) {
// declarations
var flag = 0;
var len = obj.length;
var i = 0;
var id = 1;
// looping array
for (i; i < len; i++) {
// if name matches
if (name == obj[i]['username']) {
flag = 1;
break;
} else {
// increment the id by 1
id = id + 1;
}
}
// if flag = 1 then name exits else push in array
if (flag == 0) {
// new entry push in array
obj.push({'id':id, 'username': name});
}
}
// function end
checkName('abc');
</script>
通过这种方式,您可以更快地获得结果。
注意:我没有检查传递的参数是否为空,如果您需要,可以对其进行检查或编写正则表达式以进行特定验证。
答案 20 :(得分:0)
您可以对数组进行原型设计,使其更加模块化,尝试类似这样的
Array.prototype.hasElement = function(element) {
var i;
for (i = 0; i < this.length; i++) {
if (this[i] === element) {
return i; //Returns element position, so it exists
}
}
return -1; //The element isn't in your array
};
您可以将其用作:
yourArray.hasElement(yourArrayElement)