kavkax
kavkax

Reputation: 95

Remove object in array by key

I'm trying to remove object by key in JavaScript

here is example of array

{
Account Manager: {selected: true}
Arrival: {selected: true}
Client: {selected: true}
Client Contact: {selected: true}
Created: {selected: true}
Created by: {selected: true}
Departure: {selected: true}
Destination: {selected: true}
Keywords: {selected: true}
Status: {selected: true}
}

now i'm trying to remove status and client from this array but i don't know how to make it. I've tried with this:

for(var i=0; i<list.length; i++) {
    if(list[i] == 'Status' || list[i] == 'Client') {
       list.splice(i, 1);
    }
}

Upvotes: 0

Views: 369

Answers (3)

namrata nag
namrata nag

Reputation: 1

We can use delete keywaord for that -:

delete object["keyName"];

This will remove that specific key...

Upvotes: 0

Braj Ankit
Braj Ankit

Reputation: 333

The provided sample is an Object and not an array. Since you're using AngularJS you can directly use JavaScript to remove the key from the object.

Below is a sample by simply using the delete() method

 const _object = {
      "Account Manager": { selected: true },
      "Arrival": { selected: true },
      "Client": { selected: true },
      "Client Contact": { selected: true },
      "Created": { selected: true },
      "Created by": { selected: true },
      "Departure": { selected: true },
      "Destination": { selected: true },
      "Keywords": { selected: true },
      "Status": { selected: true }
    }

    delete _object["Status"];

    console.log(_object);

Upvotes: 2

Abhisar Tripathi
Abhisar Tripathi

Reputation: 1659

We can use reduce function for that -:

let newList = Object.keys(oldList).reduce((acc, key) => {
    if(key !== 'Status' || key !== 'Client'){
        acc[key] = oldList[key]
    }
    return acc;
}, {})

Upvotes: 0

Related Questions