program story

객체의 Javascript 배열 내에 객체 값이 있는지 확인하고 배열에 새 객체를 추가하지 않는 경우

inputbox 2020. 8. 9. 10:25
반응형

객체의 Javascript 배열 내에 객체 값이 있는지 확인하고 배열에 새 객체를 추가하지 않는 경우


다음과 같은 객체 배열이있는 경우 :

[ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]

특정 사용자 이름 값이 이미 존재하는지 여부와 아무 작업도 수행하지 않는지 확인하기 위해 배열을 반복하는 방법이 있습니까?하지만 해당 사용자 이름 (및 새 ID)으로 배열에 새 개체를 추가하지 않는 경우?

감사!


여기서는 ids가 고유해야 한다고 가정했습니다 . 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

그러나이 배열에 새 사용자를 추가해야 할 때 무엇을해야하는지 명확하지 않습니다. 가장 쉬운 방법 idarray.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);

Fiddle에 연결


모범 사례는 이와 같습니다.

var arr = ["a","b","c","d"];
console.log(arr.includes("a")); //---- true;
console.log(arr.includes("k")); //---- false;
console.log(arr.includes("c")); //---- true;

나는 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 };
}

배열을 더 모듈화하기 위해 프로토 타입을 만들 수 있습니다.

    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)

Native functions of array are sometimes 3X - 5X times slower than normal loops. Plus native functions wont work in all the browsers so there is a compatibility issues.

My Code:

<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>

This way you can achieve result faster.

Note: I have not checked if parameter passed is empty or not, if you want you can put a check on it or write a regular expression for particular validation.


Accepted answer can also be written in following way using arrow function on .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 }); }
 }

xorWith in Lodash can be used to achieve this

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' } ]

Check it here :

https://stackoverflow.com/a/53644664/1084987

You can create something like if condition afterwards, like

if(!contains(array, obj)) add();

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

    }
    if ( found_two == found )
    {
        console.log("number present in the array");
    }
    else
    {
        console.log("number not present in the array");
    }
}

참고URL : https://stackoverflow.com/questions/22844560/check-if-object-value-exists-within-a-javascript-array-of-objects-and-if-not-add

반응형