0

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);
    }
}
2
  • 1
    the example you've shared is not an array it's an Object Commented Dec 16, 2019 at 9:30
  • @iam.Carrot is correct , its an object not an array. Commented Dec 16, 2019 at 9:32

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

We can use delete keywaord for that -:

delete object["keyName"];

This will remove that specific key...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.