[英]How to convert JSON string values to lowercase in Javascript?
我有一些 JSON 數據,其中包含字符串和 int 值的混合。 如何將所有字符串值轉換為小寫?
例如:
{ id: 0, name: "SAMPLe", forms: { formId: 0, id: 0, text: "Sample Text" }}
所需的 output:
{ id: 0, name: "sample", forms: { formId: 0, id: 0, text: "sample text" }}
您可以使用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)
您需要通過 object 遞歸:
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));
需要遍歷object。
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);
就我而言,我只想將屬性轉換為小寫,值(如密碼、數字...等)保持不變。
我的 ajax 回調結果集是:
result = [{FULL_NAME:xxx}, {}, {}....... {}]
我希望它是:
result = [{full_name:xxx}, {}, {}....... {}]
這是我的工作代碼:
我使用 mazillar 瀏覽器本機 api fetch() 而不是舊的 ajax 或 jquery $get 等。
// ********** must use self = this **************
// this reference vue-app. must pass it to self, then pass into callback function (success call back)
var self = this;
fetch(getUser_url).then(function (response) {
return response.json();
}).then(function (result) {
//------------------------ properties to lowercase ----------------------
// result is upper case, must convert all properties to lowercase,
// however, the value like password or number MUST remain no change.
// result = [{}, {}, {}....... {}]
var result_lower_properties= [];
var arrayLength = result.length;
for (var i = 0; i < arrayLength; i++) {
var obj = result[i];
var obj_lower_properties = {};
for (var prop in obj) {
//console.log(prop.toLowerCase())
//console.log(obj[prop])
obj_lower_properties[prop.toLowerCase()] = obj[prop]
}// for
result_lower_properties.push(obj_lower_properties)
}// for
//---------- ENd -------------- properties to lowercase ----------------------
// must use self.user, do not use this.user,
// because here, this's scope is just the function (result).
// we need this reference to vue-app,
self.user = result_lower_properties; // [{}, {}, {}]
}); // fetch(){}
使用json-case-convertor
convertor https://www.npmjs.com/package/json-case-convertor
const jcc = require('json-case-convertor');
jcc.sentenceCaseValues(jsonData)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.