0

I need to delete, in nodeJS, all of the keys which have two points or has white space or is empty.

I have this JSON:

{
    "cmd": [
        {
            "key:test": "False",
            "id": "454",
            "sales": [
                {

                    "customer_configuration": {
                        "key:points": "test value",
                         "": "empty key",
                        "some_field": "test"
                    }
                }
            ]
        }
    ]
}

target JSON:

{
    "cmd": [
        {
            "id": "454",
            "sales": [
                {
                    "customer_configuration": {
                        "some_field": "test"
                    }
                }
            ]
        }
    ]
}

How can I do this?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Amine Hatim
  • 237
  • 2
  • 7
  • 19

1 Answers1

4

You can create recursive function using for...in loop to search your data and then delete specific properties.

var obj = {
  "cmd": [{
    "key:test": "False",
    "id": "454",
    "sales": [{

      "customer_configuration": {
        "key:points": "test value",
        "": "empty key",
        "some_field": "test"
      }
    }]
  }]
}

function deleteKeys(data) {
  for (var i in data) {
    if (i.indexOf(':') != -1 || i == '') delete data[i]
    if (typeof data[i] == 'object') deleteKeys(data[i]);
  }
}

deleteKeys(obj)
console.log(obj)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
  • If you want to keep original object and create new object in your function you should check this question http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript – Nenad Vracar Jan 12 '17 at 13:04
  • Thanks Nenad it works, I tried JSON.stringify(obj) it works also – Amine Hatim Jan 12 '17 at 13:09