[javascript] 자바 스크립트는 키 값을 기준으로 배열에서 객체를 찾고 제거합니다.

ID = var 인 배열에서 객체를 찾는 방법에 대한 여러 가지 접근법을 시도했으며 발견 된 경우 배열에서 객체를 제거하고 새 객체 배열을 반환합니다.

데이터:

[
    {"id":"88","name":"Lets go testing"},
    {"id":"99","name":"Have fun boys and girls"},
    {"id":"108","name":"You are awesome!"}
]

jQuery $ grep을 사용하여 배열을 검색 할 수 있습니다.

var id = 88;

var result = $.grep(data, function(e){
     return e.id == id;
});

그러나 id == 88 일 때 전체 객체를 어떻게 삭제하고 다음과 같이 데이터를 반환 할 수 있습니까?

데이터:

[
    {"id":"99","name":"Have fun boys and girls"},
    {"id":"108","name":"You are awesome!"}
]



답변

id의 배열을 grep 할 수는 있지만 id == 88 인 전체 객체를 어떻게 삭제할 수 있습니까?

반대 술어로 간단히 필터링하십시오.

var data = $.grep(data, function(e){
     return e.id != id;
});


답변

jquery를 사용하지 않는 경우 해결책은 다음과 같습니다.

myArray = myArray.filter(function( obj ) {
  return obj.id !== id;
});


답변

이것을 단순화 할 수 있으며 여기서는 jquery를 사용할 필요가 없습니다.

var id = 88;

for(var i = 0; i < data.length; i++) {
    if(data[i].id == id) {
        data.splice(i, 1);
        break;
    }
}

목록을 반복하고 일치하는 ID, 스플 라이스를 찾은 다음 중단하여 루프를 종료하십시오.


답변

findIndex 및 array spread 연산자를 사용하여 ES6 / 2015에서이를 수행하는 새로운 방법이 있습니다.

const index = data.findIndex(obj => obj.id === id);
const newData = [
    ...data.slice(0, index),
    ...data.slice(index + 1)
]

다음과 같이 나중에 재사용 할 수있는 함수로 바꿀 수 있습니다.

function remove(array, key, value) {
    const index = array.findIndex(obj => obj[key] === value);
    return index >= 0 ? [
        ...array.slice(0, index),
        ...array.slice(index + 1)
    ] : array;
}

이렇게하면 한 가지 방법을 사용하여 다른 키로 항목을 제거 할 수 있습니다 (기준을 충족하는 객체가 없으면 원래 배열이 반환됩니다).

const newData = remove(data, "id", "88");
const newData2 = remove(data, "name", "You are awesome!");

또는 Array.prototype에 넣을 수 있습니다.

Array.prototype.remove = function (key, value) {
    const index = this.findIndex(obj => obj[key] === value);
    return index >= 0 ? [
        ...this.slice(0, index),
        ...this.slice(index + 1)
    ] : this;
};

그리고 이런 식으로 사용하십시오 :

const newData = data.remove("id", "88");
const newData2 = data.remove("name", "You are awesome!");


답변

ID가 고유하고 하나의 요소 만 제거 splice하면 트릭을 수행 한다고 가정합니다 .

var data = [
  {"id":"88","name":"Lets go testing"},
  {"id":"99","name":"Have fun boys and girls"},
  {"id":"108","name":"You are awesome!"}
],
id = 88;

console.table(data);

$.each(data, function(i, el){
  if (this.id == id){
    data.splice(i, 1);
  }
});

console.table(data);


답변

var items = [
  {"id":"88","name":"Lets go testing"},
  {"id":"99","name":"Have fun boys and girls"},
  {"id":"108","name":"You are awesome!"}
];

jQuery를 사용하는 경우 다음 과 같이 jQuery.grep을 사용 하십시오.

items = $.grep(items, function(item) {
  return item.id !== '88';
});
// items => [{ id: "99" }, { id: "108" }]

ES5 Array.prototype.filter 사용 :

items = items.filter(function(item) {
  return item.id !== '88';
});
// items => [{ id: "99" }, { id: "108" }]


답변

아마도 당신은 $.grep()기능을 찾고 있습니다 :

arr = [
  {"id":"88","name":"Lets go testing"},
  {"id":"99","name":"Have fun boys and girls"},
  {"id":"108","name":"You are awesome!"}
];

id = 88;
arr = $.grep(arr, function(data, index) {
   return data.id != id
});