2017-10-06 232 views
1

我有一個json對象,如下所示。我想通過使用下面的代碼來刪除「otherIndustry」條目及其值。如何刪除json對象的鍵值。

var updatedjsonobj = delete myjsonobj['otherIndustry']; 

如何刪除Json對象的特定鍵及其值。 下面是我的例子json對象,我想刪除「otherIndustry」鍵和它的值。

var myjsonobj = { 
     "employeeid": "160915848", 
     "firstName": "tet", 
     "lastName": "test", 
     "email": "[email protected]", 
     "country": "Brasil", 
     "currentIndustry": "aaaaaaaaaaaaa", 
     "otherIndustry": "aaaaaaaaaaaaa", 
     "currentOrganization": "test", 
     "salary": "1234567" 
    }; 
delete myjsonobj ['otherIndustry']; 
console.log(myjsonobj); 

在日誌仍然打印相同的對象,但不從對象otherIndustry「條目。

+0

的[拔下JSON對象鍵值對]可能的複製(https://stackoverflow.com/questions/24770887/remove-key-value-pair-from-json-object) –

+0

你的代碼應該可以工作,你可以創建一個MVCE https://stackoverflow.com/help/mcve – gurvinder372

+0

刪除myObj.other.key1; [如此示例中所示](https://stackoverflow.com/questions/1219630/remove-a-json-attribute/1219633#1219633) –

回答

6

delete運營商用於remove對象property

delete操作返回新的對象,只返回一個boolean

在另一方面,解釋器執行var updatedjsonobj = delete myjsonobj['otherIndustry'];後,updatedjsonobj變量將存儲boolean 值。

如何刪除Json對象的特定鍵及其值?

您只需要知道屬性名稱即可將其從對象的屬性中刪除。

delete myjsonobj['otherIndustry']; 

let myjsonobj = { 
 
    "employeeid": "160915848", 
 
    "firstName": "tet", 
 
    "lastName": "test", 
 
    "email": "[email protected]", 
 
    "country": "Brasil", 
 
    "currentIndustry": "aaaaaaaaaaaaa", 
 
    "otherIndustry": "aaaaaaaaaaaaa", 
 
    "currentOrganization": "test", 
 
    "salary": "1234567" 
 
} 
 
delete myjsonobj['otherIndustry']; 
 
console.log(myjsonobj);

如果你想刪除key當你知道的價值,你可以使用Object.keys函數返回給定對象自己的枚舉的屬性的數組。

let value="test"; 
 
let myjsonobj = { 
 
     "employeeid": "160915848", 
 
     "firstName": "tet", 
 
     "lastName": "test", 
 
     "email": "[email protected]", 
 
     "country": "Brasil", 
 
     "currentIndustry": "aaaaaaaaaaaaa", 
 
     "otherIndustry": "aaaaaaaaaaaaa", 
 
     "currentOrganization": "test", 
 
     "salary": "1234567" 
 
} 
 
Object.keys(myjsonobj).forEach(function(key){ 
 
    if(myjsonobj[key]==value) 
 
    delete myjsonobj[key]; 
 
}); 
 
console.log(myjsonobj);

+0

因此,不管返回值如何,是否將按照OP的代碼從對象中刪除'key:value'? – Rajesh

1

按照此,它可以像你在找什麼:

var obj = { 
 
    Objone: 'one', 
 
    Objtwo: 'two' 
 
}; 
 

 
var key = "Objone"; 
 
delete obj[key]; 
 
console.log(obj); // prints { "objtwo": two}