Search code examples
javascriptjavascript-objects

How to delete any other fields than the specified ones in javascript object?


I have a js object like this

{
    "firstName": "percy",
    "lastName": "jackson",
    "languages":["Node", "english"],
    "country": "Canada"
}

the acceptable fields are: firstName, lastName, languages, country

If I get object like this:

{
    "firstName": "percy",
    "lastName": "jackson",
    "email":"[email protected]",
    "languages":["Node", "english"],
    "phoneNumber": "872612334",
    "dob": "04/06/1990",
    "countryCode": "+21",
    "country": "Canada"
}

I want to truncate all the extra fields which are not acceptable, how do I do this, deleting them manually one by one is not allowed(since everytime we might not have the same set of extra fields), though only aim is to keep the acceptable fields.


Solution

  • You could put the acceptable keys in an array, and then loop over the object keys removing the ones that don't match. Note, that this method mutates the object, rather than creating a new one.

    const ok = ['firstName', 'lastName', 'languages', 'country'];
    
    const obj = {
        "firstName": "percy",
        "lastName": "jackson",
        "email":"[email protected]",
        "languages":["Node", "english"],
        "phoneNumber": "8726905758",
        "dob": "04/06/1990",
        "countryCode": "+21",
        "country": "Canada"
    }
    
    Object.keys(obj).forEach(key => {
      if (!ok.includes(key)) delete obj[key];
    });
    
    console.log(obj);

    Additional documentation