繁体   English   中英

如何用'null'字符串替换javaScript对象中的所有null值?

[英]How to replace all null values in javaScript object with 'null' string?

假设我有这个js对象:

{"a": null, "b": 5, "c": 0, d: "", e: [1,2,null, 3]}

这就是我想要得到的:

{"a": "null", "b": 5, "c": 0, d: "", e: [1,2,"null", 3]}

我唯一的想法是使用:

function nullToString(v) {
    return JSON.parse(JSON.stringify(v).split(":null").join(":\"null\""));
}

但是,与我要实现的目标相比,这似乎是一项非常昂贵的操作。

如果有来自jQuery或underscore.js的任何有用的方法,那就太好了。

这适用于您提供的数据:

var data = {"a": null, "b": 5, "c": 0, d: "", e: [1,2,null, 3]};

function nullToString(value) { 

    function recursiveFix(o) {
        // loop through each property in the provided value
        for(var k in o) {
            // make sure the value owns the key
            if (o.hasOwnProperty(k)) { 
                if (o[k]===null) {
                    // if the value is null, set it to 'null'
                    o[k] = 'null';
                } else if (typeof(o[k]) !== 'string' && o[k].length > 0) {
                    // if there are sub-keys, make a recursive call
                    recursiveFix(o[k]);
                }
            }
        }
    }

    var cloned = jQuery.extend(true, {}, value)
    recursiveFix(cloned);
    return cloned;
}

console.log(nullToString(data));

基本前提是递归地遍历对象的属性,如果该值为null,则替换该值。

当然,您问题的根源是“我想要更快的东西”。 我邀请您介绍您的解决方案,此解决方案以及您遇到的任何其他解决方案。 您的结果可能令人惊讶。

这是一个非常简单的示例:

 function convertObjectValuesRecursive(obj, target, replacement) { obj = {...obj}; Object.keys(obj).forEach((key) => { if (obj[key] == target) { obj[key] = replacement; } else if (typeof obj[key] == 'object' && !Array.isArray(obj[key])) { obj[key] = convertObjectValuesRecursive(obj[key], target, replacement); } }); return obj; } 

该函数采用三个参数,即obj,目标值和替换值,并将用替换值递归替换所有目标值(包括嵌套对象中的值)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM