Programming

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

procodes 2020. 7. 29. 22:18
반응형

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


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
});

sift이와 같은 작업과 훨씬 고급 기능을위한 강력한 컬렉션 필터입니다. 브라우저의 클라이언트 측 또는 node.js의 서버 측에서 작동합니다.

var collection = [
    {"id":"88","name":"Lets go testing"},
    {"id":"99","name":"Have fun boys and girls"},
    {"id":"108","name":"You are awesome!"}
];
var sifted = sift({id: {$not: 88}}, collection);

It supports filters like $in, $nin, $exists, $gte, $gt, $lte, $lt, $eq, $ne, $mod, $all, $and, $or, $nor, $not, $size, $type, and $regex, and strives to be API-compatible with MongoDB collection filtering.


Array.prototype.removeAt = function(id) {
    for (var item in this) {
        if (this[item].id == id) {
            this.splice(item, 1);
            return true;
        }
    }
    return false;
}

This should do the trick, jsfiddle


Make sure you coerce the object id to an integer if you test for strict equality:

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

Demo


If you are using underscore js, it is easy to remove object based on key. http://underscorejs.org. Example:

  var temp1=[{id:1,name:"safeer"},  //temp array
             {id:2,name:"jon"},
             {id:3,name:"James"},
             {id:4,name:"deepak"},
             {id:5,name:"ajmal"}];

  var id = _.pluck(temp1,'id'); //get id array from temp1
  var ids=[2,5,10];             //ids to be removed
  var bool_ids=[];
  _.each(ids,function(val){
     bool_ids[val]=true;
  });
  _.filter(temp1,function(val){
     return !bool_ids[val.id];
  });

참고URL : https://stackoverflow.com/questions/21659888/javascript-find-and-remove-object-in-array-based-on-key-value

반응형