[javascript] 객체 속성을 기준으로 배열 요소 제거

다음과 같은 객체 배열이 있습니다.

var myArray = [
    {field: 'id', operator: 'eq', value: id},
    {field: 'cStatus', operator: 'eq', value: cStatus},
    {field: 'money', operator: 'eq', value: money}
];

속성을 기준으로 특정 항목을 제거하려면 어떻게합니까?

예를 들어 ‘money’를 필드 속성으로 사용하여 배열 객체를 어떻게 제거합니까?



답변

하나의 가능성 :

myArray = myArray.filter(function( obj ) {
    return obj.field !== 'money';
});

filter새로운 배열 이 생성됩니다. 원래 변수 myArray를 새 참조로 업데이트하더라도 원래 배열을 참조하는 다른 변수는 필터링 된 데이터를 가져 오지 않습니다 . 주의해서 사용하십시오.


답변

배열을 반복 splice하고 원하지 않는 배열을 반복하십시오 . 사용하기 쉽도록 뒤로 반복하여 배열의 실제 특성을 고려하지 않아도됩니다.

for (var i = myArray.length - 1; i >= 0; --i) {
    if (myArray[i].field == "money") {
        myArray.splice(i,1);
    }
}


답변

field 속성으로 두 번째 객체를 제거한다고 가정 해보십시오.

ES6을 사용하면 이처럼 쉽습니다.

myArray.splice(myArray.findIndex(item => item.field === "cStatus"), 1)


답변

lodash의 findIndex 를 사용 하여 특정 요소의 색인을 가져온 다음이를 사용하여 결합 할 수 있습니다.

myArray.splice(_.findIndex(myArray, function(item) {
    return item.value === 'money';
}), 1);

최신 정보

ES6의 findIndex ()를 사용할 수도 있습니다

findIndex () 메소드는 제공된 테스트 함수를 만족하는 배열의 첫 번째 요소 색인을 리턴합니다. 그렇지 않으면 -1이 반환됩니다.

myArray.splice(myArray.findIndex(myArray, function(item) {
    return item.value === 'money';
}), 1);


답변

jQuery grep을 사용하는 또 다른 옵션이 있습니다. 전달 true함수와 일치 GREP 제거합니다 항목을 보장하기 위해 세 번째 매개 변수로.

users = $.grep(users, function(el, idx) {return el.field == "money"}, true)

이미 jQuery를 사용하고 있다면 shim이 필요하지 않으므로을 사용하는 대신 유용 할 수 있습니다 Array.filter.


답변

ES6에서는 한 줄만 있습니다.

const arr = arr.filter(item => item.key !== "some value");

🙂


답변

다음은 jQuery를 사용하지 않는 경우의 코드입니다. 데모

var myArray = [
    {field: 'id', operator: 'eq', value: 'id'},
    {field: 'cStatus', operator: 'eq', value: 'cStatus'},
    {field: 'money', operator: 'eq', value: 'money'}
];

alert(myArray.length);

for(var i=0 ; i<myArray.length; i++)
{
    if(myArray[i].value=='money')
        myArray.splice(i);
}

alert(myArray.length);

많은 기능을 가진 밑줄 라이브러리를 사용할 수도 있습니다.

Underscore 는 많은 기능적 프로그래밍 지원을 제공하는 JavaScript 용 유틸리티 벨트 라이브러리입니다.