如果我有以下对象数组:
[ { 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)?
谢谢!
当前回答
点击这里查看:
https://stackoverflow.com/a/53644664/1084987
你可以在后面创建if条件,比如
if(!contains(array, obj)) add();
其他回答
假设我们有一个对象数组,你想检查value of 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
}
你可以建立你的数组原型,使它更模块化,尝试这样的东西
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)
Lodash中的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' } ]
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');
}
}
接受的答案也可以这样写,在。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 }); }
}