如何从json中删除空白字段?

时间:2018-05-21 21:17:46

标签: javascript json

所以我得到了一个json,我必须清除所有的空白'领域。被视为空白的字段是:

  • 空数组或对象,
  • 带有空格的字符串(""或""),
  • null值。

这是我到目前为止所做的:

const isBlank = (val) => {
    if(val === null ) {
        return true
    }
    if(typeof val === 'string'){
        return val.trim().length === 0;
    }
    return val.length === 0
};


function clean(jsonInput) {
    Object.keys(jsonInput).forEach( key => {
        if(typeof jsonInput[key] === 'object' && !isEmpty(jsonInput[key])){
            clean(jsonInput[key])
        }else {
            isEmpty(jsonInput[key_field]) && delete jsonInput[key]
        }
    })

}

这是我正在使用的jsonInput

{
    "print": "notBlank",
    "this": "notBlank",
    "example": "notBlank",
    "blank": null,
    "allBlanks": [
        {
            "from": "",
            "blank0": null
        }
    ],
    "att2": {
        "blank1": "",
        "blank2": []
    },
    "att3": {
        "one": "1",
        "two": "2",
        "three": "3",
        "blank3": " "
    }
}

这应该是输出:

{
    "print": "notBlank",
    "this": "notBlank",
    "example": "notBlank",
    "att3": {
        "one": "1",
        "two": "2",
        "three": "3"
    }
}

相反,我得到了这个:

{
    "print": "notBlank",
    "this": "notBlank",
    "example": "notBlank",
    "allBlanks": [{ }],
    "att2": {},
    "att3": {
        "one": "1",
        "two": "2",
        "three": "3",
    }
}

接缝就像我无法移除物体......任何想法我做错了什么?我能以任何方式修复它。

还有一种方法可以做到这一点,以便我不会更改原始对象,而是复制,可能是mapfilter

2 个答案:

答案 0 :(得分:3)

这里的主要问题是[{}]未定义为“空”,因为它是一个长度为1的数组,其中包含一个对象。但是,因为您希望将空对象视为空,因此将空对象的数组设置为空,您还需要递归isEmpty函数内部以覆盖这些角度。

注意添加到isEmpty的数组和对象的两次递归调用。

至于复制,快速脏的方法是首先进行stringify然后解析json。您可以使用行

在代码底部看到这一点
var jsonCopy = JSON.parse(JSON.stringify(json));

还有更复杂的深度复制方式,请阅读What is the most efficient way to deep clone an object in JavaScript?以获取更多信息。

const isEmpty = (val) => {
    if(val === null ) {
        return true
    }
    if(typeof val === 'string'){
        return val.trim().length === 0;
    }
    if(val instanceof Array){
        if( val.length === 0 ) return true;
        return val.every( v => 
          isEmpty(v)
        );
    }
    if(val === Object(val)){
        if(Object.keys(val).length == 0) return true;
        return Object.values(val).every( 
            v => isEmpty(v)
        );
    }
    return val.length === 0;
};


function clean(jsonInput) {
    Object.keys(jsonInput).forEach( key =>     {
        if(typeof jsonInput[key] === 'object' && !isEmpty(jsonInput[key])){
            clean(jsonInput[key])
        }else {
            isEmpty(jsonInput[key]) && delete jsonInput[key]
        }
    })
}

var json = {
    "print": "notBlank",
    "this": "notBlank",
    "example": "notBlank",
    "blank": null,
    "allBlanks": [
        {
            "from": "",
            "blank0": null
        }
    ],
    "att2": {
        "blank1": "",
        "blank2": []
    },
    "att3": {
        "one": "1",
        "two": "2",
        "three": "3",
        "blank3": " "
    }
};
var jsonCopy = JSON.parse(JSON.stringify(json));
clean(jsonCopy);
console.log(jsonCopy);

答案 1 :(得分:0)

lodash

中已经存在这样的一些功能

https://lodash.com/docs/4.17.10#omitBy

  

避免在javascript中使用删除,它的速度慢而且不是很好的实践

示例:

var _ = require("lodash")

var oldObj = {a:1, b:2, c:null, d:"aa"}

var newObj = _.omitBy(oldObj, (value, key) => 
                              _.isNull(value) || 
                              (_.isString(value) && _.isEmpty(value)) ||
                              (_.isArray(value) && _.isEmpty(value))  );
console.log("Final", newObj) //Final { a: 1, b: 2, d: 'aa' }
  

isEmpty 如果值为数字https://lodash.com/docs/4.17.10#isEmpty则返回true

编辑:

  

关键字删除会在严格模式https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete

中引发异常