how to remove json object key and value.?

后端 未结 6 1335
忘了有多久
忘了有多久 2021-02-01 02:02

I have a json object as shown below. where i want to delete the \"otherIndustry\" entry and its value by using below code which doesn\'t worked.

var updatedjsono         


        
6条回答
  •  礼貌的吻别
    2021-02-01 02:25

    There are several ways to do this, lets see them one by one:

    1. delete method: The most common way

    const myObject = {
        "employeeid": "160915848",
        "firstName": "tet",
        "lastName": "test",
        "email": "test@email.com",
        "country": "Brasil",
        "currentIndustry": "aaaaaaaaaaaaa",
        "otherIndustry": "aaaaaaaaaaaaa",
        "currentOrganization": "test",
        "salary": "1234567"
    };
    
    delete myObject['currentIndustry'];
    // OR delete myObject.currentIndustry;
      
    console.log(myObject);

    1. By making key value undefined: Alternate & a faster way:

    let myObject = {
        "employeeid": "160915848",
        "firstName": "tet",
        "lastName": "test",
        "email": "test@email.com",
        "country": "Brasil",
        "currentIndustry": "aaaaaaaaaaaaa",
        "otherIndustry": "aaaaaaaaaaaaa",
        "currentOrganization": "test",
        "salary": "1234567"
      };
    
    myObject.currentIndustry = undefined;
    myObject = JSON.parse(JSON.stringify(myObject));
    
    console.log(myObject);

    1. With es6 spread Operator:

    const myObject = {
        "employeeid": "160915848",
        "firstName": "tet",
        "lastName": "test",
        "email": "test@email.com",
        "country": "Brasil",
        "currentIndustry": "aaaaaaaaaaaaa",
        "otherIndustry": "aaaaaaaaaaaaa",
        "currentOrganization": "test",
        "salary": "1234567"
    };
    
    
    const {currentIndustry, ...filteredObject} = myObject;
    console.log(filteredObject);

    Or if you can use omit() of underscore js library:

    const filteredObject = _.omit(currentIndustry, 'myObject');
    console.log(filteredObject);
    

    When to use what??

    If you don't wanna create a new filtered object, simply go for either option 1 or 2. Make sure you define your object with let while going with the second option as we are overriding the values. Or else you can use any of them.

    hope this helps :)

提交回复
热议问题