Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 280
orszaczky Avatar asked Jan 05 '16 09:01

orszaczky


4 Answers

We now use object-scan for data processing tasks like this. It's very powerful once you wrap your head around it. Here is how you'd answer your questions

// const objectScan = require('object-scan');

const prune = (input) => objectScan(['**.options'], {
  rtn: 'count',
  filterFn: ({ parent, property }) => {
    delete parent[property];
  }
})(input);

const obj = { items: [{ name: 'Item 1', value: '500', options: [{}, {}] }, { name: 'Item 2', value: '300', options: [{}, {}] }], name: 'Category', options: [{}, {}] };

console.log(prune(obj));
// => 3

console.log(obj);
// => { items: [ { name: 'Item 1', value: '500' }, { name: 'Item 2', value: '300' } ], name: 'Category' }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/[email protected]"></script>

Disclaimer: I'm the author of object-scan

like image 176
vincent Avatar answered Oct 19 '22 00:10

vincent


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") {
         delete obj.property
         let newJsonData= this.removeProp(obj[property], propToDelete);
         obj[property]= newJsonData
      } else {
          if (property === propToDelete) {
            delete obj[property];
          }
        }
    }
    return obj
}
like image 32
Sumanth Avatar answered Oct 19 '22 00:10

Sumanth


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 obj[key];
        }
    }
    return obj;
}

and use it like

var newObject = filterObject(old_json, "option");
like image 24
void Avatar answered Oct 19 '22 01:10

void


A little modification of void's answer that allows for deletion of propertise which are also objects

function filterObject(obj, key) {
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (i == key) {
            delete obj[key];
        } else if (typeof obj[i] == 'object') {
            filterObject(obj[i], key);
        }
    }
    return obj;
}
like image 44
sboyd Avatar answered Oct 19 '22 00:10

sboyd