我有一个 json 对象,如下所示。我想使用下面的代码删除“otherIndustry”条目及其值,但该代码不起作用。
var updatedjsonobj = delete myjsonobj['otherIndustry'];
如何删除 Json 对象特定的键及其值。 下面是我的示例 json 对象,我想在其中删除“otherIndustry”键及其值。
var myjsonobj = {
"employeeid": "160915848",
"firstName": "tet",
"lastName": "test",
"email": "test@email.com",
"country": "Brasil",
"currentIndustry": "aaaaaaaaaaaaa",
"otherIndustry": "aaaaaaaaaaaaa",
"currentOrganization": "test",
"salary": "1234567"
};
delete myjsonobj ['otherIndustry'];
console.log(myjsonobj);
日志仍然打印相同的对象,而不从对象中删除“otherIndustry”条目。
最佳答案
delete
运算符用于删除
对象属性
。
delete
运算符不返回新对象,仅返回boolean
:true 或 错误。
另一方面,解释器执行 var Updatedjsonobj = delete myjsonobj['otherIndustry'];
后, updatedjsonobj
变量将存储一个 boolean
值。
How to remove Json object specific key and its value ?
您只需要知道属性名称即可将其从对象的属性中删除。
delete myjsonobj['otherIndustry'];
let myjsonobj = {
"employeeid": "160915848",
"firstName": "tet",
"lastName": "test",
"email": "test@email.com",
"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": "test@email.com",
"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);
关于javascript - 如何删除json对象的键和值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46599519/