如何删除json对象的键和值? [英] how to remove json object key and value.?
问题描述
我有一个json对象,如下所示.我想使用以下无效的代码删除"otherIndustry"条目及其值.
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 updatedjsonobj = delete myjsonobj['otherIndustry'];
如何删除Json对象特定的键及其值. 以下是我要删除"otherIndustry"键及其值的示例json对象.
How to remove Json object specific key and its value. Below is my example json object where i want to remove "otherIndustry" key and its value.
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"条目.
where the log still prints the same object without removing 'otherIndustry' entry from the object.
推荐答案
delete
运算符用于remove
对象property
.
delete
运算符不返回新对象,仅返回boolean
: true 或 false .
delete
operator does not returns the new object, only returns a boolean
: true or false.
另一方面,在解释器执行var updatedjsonobj = delete myjsonobj['otherIndustry'];
之后,updatedjsonobj
变量将存储boolean
值.
In the other hand, after interpreter executes var updatedjsonobj = delete myjsonobj['otherIndustry'];
, updatedjsonobj
variable will store a boolean
value.
如何删除Json对象特定的键及其值?
How to remove Json object specific key and its value ?
您只需要知道属性名称即可从对象的属性中删除它.
You just need to know the property name in order to delete it from the object's properties.
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
函数,该函数返回给定对象自己的可枚举属性的数组.
If you want to remove a key
when you know the value you can use Object.keys
function which returns an array of a given object's own enumerable properties.
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);
这篇关于如何删除json对象的键和值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!