How to remove a property from nested javascript objects any level deep?

大城市里の小女人 提交于 2019-12-07 07:10:16

问题


Let's say I have nested objects, like:

var obj = {
    "items":[
        {
            "name":"Item 1", 
            "value": "500",
            "options": [{...},{...}]
        },
        {
            "name":"Item 2", 
            "value": "300",
            "options": [{...},{...}]
        }
    ],
    "name": "Category",
    "options": [{...},{...}]
};

I want to remove the options property from any level deep from all the objects. Objects can be nested within objects, and arrays as well.

We're currently using Lodash in the project, but I'm curious about any solutions.


回答1:


There is no straight forward way to achieve this, however you can use this below function to remove a key from JSON.

function filterObject(obj, key) {
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
            filterObject(obj[i], key);
        } else if (i == key) {
            delete key;
        }
    }
    return obj;
}

and use it like

var newObject = filterObject(old_json, "option");



回答2:


Modifying the above solution, To delete "dataID" which appears multiple times in my JSON . mentioned below code works fine.

var candidate = {
  "__dataID__": "Y2FuZGlkYXRlOjkuOTI3NDE5MDExMDU0Mjc2",
  "identity": {
    "__dataID__": "aWRlbnRpdHk6NjRmcDR2cnhneGE3NGNoZA==",
    "name": "Sumanth Suvarnas"
  },  
};

candidate = removeProp(candidate, "__dataID__")

console.log(JSON.stringify(candidate, undefined, 2));

function removeProp(obj, propToDelete) {
   for (var property in obj) {
      if (typeof obj[property] == "object") {
         let objectToCheck = obj[property];
         delete obj.property
         let newJsonData= this.removeProp(obj[property], propToDelete);
         obj[property]= newJsonData
      } else {
          if (property === propToDelete) {
            delete obj[property];
          }
        }
    }
    return obj
}


来源:https://stackoverflow.com/questions/34607701/how-to-remove-a-property-from-nested-javascript-objects-any-level-deep

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!