javascript - 如何删除json对象的键和值?

标签 javascript jquery json object

我有一个 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/

相关文章:

javascript - 如何在 php 中使用数组显示选择多个下拉列表?

python - 加载 JSON 并获取某些数据 (Python)

javascript - 如何访问带有奇数字符(如 "#name")的属性?

javascript - 你如何在 javascript 中使用 css 关键帧动画

php - 如果页面上存在 JavaScript 错误,谷歌地图是否无法加载?

javascript - 访问动态参数 EmberJS

mysql - 如何使用 Laravel 从存储在数组中的单列获取数据?

javascript - 为什么这个 SVG 在 Chrome 上运行良好,但在 Firefox 上不可见?

c# - ASP.NET C# : Call serverside function together with Jquery BlockUI

javascript - Materialise 模态未打开