如何用'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、目标值和替换值,并将用替换值递归地替换所有目标值(包括嵌套对象中的值)。
相关文章:
- 如何将返回一串数字的 JSON 属性转换为日期
- 在一串数字中查找特定值
- 如何将一串数字转换为数组
- javascript对象(如array&一串
- 如何用Javascript生成一串数字和字母
- 加载一串 markdown 属性作为 JavaScript 对象
- 为什么一串数字的工作方式与新日期中的实际数字不同
- 如何将一串数字和数学运算符变成整数答案?- JavaScript
- 传给玉的东西最后是一串
- 色调转换一串颜色
- 如何在饼干中剪下一串字母
- 如何用'null'一串
- 是 JavaScript 中的一串空白真或假
- Node JS -在一个新进程中执行一串代码
- 有没有任何字符串方法,能让我把一串数字,转换成一串数字和字母
- 一串没有RegEX的Match()
- 对一串数字进行排序,每个数字里面都有一个字母.确保在原始数组中保持相同的重复项位置
- 在javascript中创建一串数字,每个数字都有限制
- 我如何从一串用冒号分隔的角色中获得数据
- 如何获取一串参数并返回其中包含的点数(.)