如何用'null'一串

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

本文关键字:一串 null 何用      更新时间:2023-09-26

假设我有这个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、目标值和替换值,并将用替换值递归地替换所有目标值(包括嵌套对象中的值)。