다음과 같은 객체 배열이있는 경우 :
[ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
특정 사용자 이름 값이 이미 존재하는지 여부와 아무것도하지 않는지 확인하기 위해 배열을 반복하는 방법이 있습니까?하지만 해당 사용자 이름 (및 새 ID)으로 배열에 새 객체를 추가하지 않는 경우?
감사!
답변
나는 id
여기서 s가 독창적 이라고 가정했습니다 . 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'));
답변
기존 사용자 이름을 확인하는 것은 쉽지 않습니다.
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 고유성을 보장하지만 일부 요소가 끝날 경우이 배열을 조금 이상하게 보입니다.
답변
이 작은 스 니펫은 저에게 효과적입니다 ..
const arrayOfObject = [{ id: 1, name: 'john' }, {id: 2, name: 'max'}];
const checkUsername = obj => obj.name === 'max';
console.log(arrayOfObject.some(checkUsername))
답변
이것이이 문제를 해결하는 가장 짧은 방법이라고 생각합니다. 여기에서는 .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);
답변
이것은 @ 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)
답변
허용되는 답변은 다음의 화살표 기능을 사용하여 다음과 같이 작성할 수도 있습니다.
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 }); }
}
답변
다음은 .map()
and를 사용하는 ES6 메소드 체인입니다 .includes()
.
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
}
- 기존 사용자를 매핑하여 사용자 이름 문자열 배열을 만듭니다.
- 해당 사용자 이름 배열에 새로운 사용자 이름이 포함되어 있는지 확인
- 존재하지 않으면 새 사용자를 추가하십시오.
