删除符合某些条件的键

时间:2017-01-12 12:52:07

标签: javascript json node.js

我需要在nodeJS中删除所有具有两个点或具有空格或为空的键。

我有这个JSON:

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

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

目标JSON:

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

我该怎么做?

1 个答案:

答案 0 :(得分:4)

您可以使用for...in循环创建递归函数来搜索数据,然后搜索delete特定属性。

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)