Pawan
Pawan

Reputation: 32321

How to delete a certain Object from an Array

I have an Array as shown below

var test = 
[
  {
    "name": "Mike",
    "incentives": "23.45",
    "id": "1"
  },
  {
    "name": "Larsen",
    "incentives": "34.78",
    "id": "2"
  },
  {
    "name": "Steve",
    "incentives": "26.78",
    "id": "3"
  }
]

I want to remove a certain Object

I have tried as shown below

var idtoberemoved = 2

test = test.filter((obj) => typeof obj.id = '2');

https://jsfiddle.net/o2gxgz9r/65584/

Upvotes: 0

Views: 107

Answers (4)

Sreekanth
Sreekanth

Reputation: 3130

If you are looking for more than one id being removed, here is one more way to accomplish using reduce. This is not very different from the other approaches and answers, but a different way to accomplish the ask.

var test = [{
    "name": "Mike",
    "incentives": "23.45",
    "id": "1"
  },
  {
    "name": "Larsen",
    "incentives": "34.78",
    "id": "2"
  },
  {
    "name": "Steve",
    "incentives": "26.78",
    "id": "3"
  }
];

function removeItem(idList) {

  var result = test.reduce(function(output, currentObject) {
    if (!idList.includes(currentObject.id)) {
      output.push(currentObject);
    }
    return output;
  }, []);
  return result;
}


console.log(removeItem(["2", '3']))

Upvotes: 0

chebaby
chebaby

Reputation: 7730

    var test = [
        {
            "name": "Mike",
            "incentives": "23.45",
            "id": "1"
        },
        {
            "name": "Larsen",
            "incentives": "34.78",
            "id": "2"
        },
        {
            "name": "Steve",
            "incentives": "26.78",
            "id": "3"
        }
    ];
    
    var filtered = test.filter(function(object) {
    
        return object.id != 2;
    });
    
    console.log(filtered);

Upvotes: 0

Taplar
Taplar

Reputation: 24965

You could find the index of the element in the array, and use splice to remove it.

var test = [{
    "name": "Mike",
    "incentives": "23.45",
    "id": "1"
  },
  {
    "name": "Larsen",
    "incentives": "34.78",
    "id": "2"
  },
  {
    "name": "Steve",
    "incentives": "26.78",
    "id": "3"
  }
];

//Use splice to remove the element
test.splice(
  //find the index of the element to be removed
  test.indexOf(test.find(function(element){ return element.id === "2"; }))
  //remove 1 element from the index found
  , 1
);

console.log(test);

Upvotes: 1

Arup Rakshit
Arup Rakshit

Reputation: 118261

typeof obj.id will give you "string", and you want to filter out the objects whose id property is not equalt to "2". So, it should be

test.filter(obj => obj.id !== '2');

In JS, = is for assignment, not for equality test. We use ==, ===, !==, != for equality tests. There are difference between == and ===, but that is a whole subject.

Upvotes: 0

Related Questions