我有一些JSON数据,其中包含string和int值的混合。如何将所有字符串值转换为小写?
例如:
{ id: 0, name: "SAMPLe", forms: { formId: 0, id: 0, text: "Sample Text" }}
期望的输出:
{ id: 0, name: "sample", forms: { formId: 0, id: 0, text: "sample text" }}
答案 0 :(得分:1)
您需要通过对象递归:
https://jsbin.com/lugokek/1/edit?js,console
var x = { id: 0, name: "SAMPLe", forms: { formId: 0, id: 0, text: "Sample Text" }};
function lower(obj) {
for (var prop in obj) {
if (typeof obj[prop] === 'string') {
obj[prop] = obj[prop].toLowerCase();
}
if (typeof obj[prop] === 'object') {
lower(obj[prop]);
}
}
return obj;
}
console.log(lower(x));
答案 1 :(得分:1)
您可以使用JSON.stringify()
,JSON.parse()
,typeof
var data = {
id: 0,
name: "SAMPLe",
forms: {
formId: 0,
id: 0,
text: "Sample Text"
}
};
var res = JSON.parse(JSON.stringify(data, function(a, b) {
return typeof b === "string" ? b.toLowerCase() : b
}));
console.log(res)
答案 2 :(得分:0)
您需要遍历该对象。
function lowerStrings(obj) {
for (let attr in obj) {
if (typeof obj[attr] === 'string') {
obj[attr] = obj[attr].toLowerCase();
} else if (typeof obj[attr] === 'object') {
lowerStrings(obj[attr]);
}
}
}
var obj = {
id: 0,
name: "SAMPLe",
forms: { formId: 0, id: 0, text: "Sample Text" }
};
lowerStrings(obj);
console.log(obj);

答案 3 :(得分:0)
就我而言,我只希望将属性转换为小写,而值(如密码,数字等)保持不变。
我的ajax回调结果集是:
Invoke
我希望它是:
result = [{FULL_NAME:xxx}, {}, {}....... {}]
这是我的工作代码:
我使用mazillar浏览器本机api fetch()代替了旧的ajax或jquery $ get等。
result = [{full_name:xxx}, {}, {}....... {}]