如果我有以下对象数组:
[ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
是否有一种方法通过数组循环检查特定的用户名值是否已经存在,如果它不做任何事情,但如果它没有添加一个新对象到数组的用户名(和新ID)?
谢谢!
如果我有以下对象数组:
[ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
是否有一种方法通过数组循环检查特定的用户名值是否已经存在,如果它不做任何事情,但如果它没有添加一个新对象到数组的用户名(和新ID)?
谢谢!
当前回答
出于某种原因,我确实尝试了上述步骤,但对我来说似乎并不管用,但这是我对自己问题的最终解决方案,可能对阅读本文的任何人都有帮助:
let pst = post.likes.some( (like) => { //console.log(like.user, req.user.id);
if(like.user.toString() === req.user.id.toString()){
return true
} } )
这帖子。点赞是喜欢某篇文章的用户的数组。
其他回答
检查现有的用户名相当简单:
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的新元素。长度+ 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的唯一性,但如果将一些元素从数组末尾删除,则会使该数组看起来有点奇怪。
你可以建立你的数组原型,使它更模块化,尝试这样的东西
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)
我假设这里的id是唯一的。Find是一个很棒的数组方法,用于检查数组中是否存在东西:
Const arr = [{id: 1,用户名:'fred'}, {id: 2,用户名:'bill'}, {id: 3,用户名:'ted'}]; 函数add(arr, name) { Const {length} = arr; Const id =长度+ 1; Const found = arr。求(el => el。用户名=== name); 如果(!发现)arr。推送({id,用户名:name}); 返回arr; } console.log(添加(arr“ted”)); console.log(添加(加勒比海盗,“黛西”));
接受的答案也可以这样写,在。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 }); }
}
function number_present_or_not() {
var arr = [2, 5, 9, 67, 78, 8, 454, 4, 6, 79, 64, 688];
var found = 6;
var found_two;
for (i = 0; i < arr.length; i++) {
if (found == arr[i]) {
found_two = arr[i];
break;
}
}
if (found_two == found) {
console.log('number present in the array');
} else {
console.log('number not present in the array');
}
}