My code works but i think it's not efficient, may be there is a more efficient way. I have a Json (data.json):
{
"Testaments":[
{
"Books":[
{
"Chapters":[
{
"Verses":[
{
"ID":2,
"Text":"Au commencement, Dieu créa les cieux et la terre."
},
{
"ID":2,
"Text":"La terre était informe et vide: il y avait des ténèbres à la surface de l'abîme, et l'esprit de Dieu se mouvait au-dessus des eaux."
}
]
}
]
}
]
}
]
}
i want transform key object in uppercase, (i don't want use regex):
const fs = require("fs");
const url = "./data.json";
var camalize = function camalize(str) {
return str
.toLowerCase()
.replace(/[^a-zA-Z0-9]+(.)/g, (m, chr) => chr.toUpperCase());
};
fs.readFile(url, "utf8", (err, data) => {
if (err) {
console.error(err);
return;
}
var obj = JSON.parse(data);
changeName(obj);
obj.testaments.forEach((elem, ind) => {
changeName(elem);
obj.testaments[ind].books.forEach((elem2, ind2) => {
changeName(elem2);
obj.testaments[ind].books[ind2].chapters.forEach((elem3, ind3) => {
changeName(elem3);
obj.testaments[ind].books[ind2].chapters[ind3].verses.forEach(
(elem4) => {
changeName(elem4);
}
);
});
});
});
function changeName(obj) {
for (const property in obj) {
const newName = camalize(property);
obj[newName] = obj[property];
//console.log(typeof obj[newName]);
delete obj[property];
}
}
console.log("finish");
fs.writeFileSync(`export/export.json`, JSON.stringify(obj, null, 2));
});
i doesn't want to make a callback hell with the foreach method, is the a more efficient method to do that ?
Thanks
Change object properties recursively:
const fs = require("fs");
const url = "./data.json";
var camalize = function camalize(str) {
return str
.toLowerCase()
.replace(/[^a-zA-Z0-9]+(.)/g, (m, chr) => chr.toUpperCase());
};
fs.readFile(url, "utf8", (err, data) => {
if (err) {
console.error(err);
return;
}
var obj = JSON.parse(data);
changeName(obj);
function updateKey(obj, k) {
const newName = camalize(k);
obj[newName] = obj[k];
delete obj[k];
return newName;
}
function changeName(obj) {
for (const k in obj) {
if (typeof propValue === 'object' && obj[k] !== null && !Array.isArray(obj[k])) {
changeName(obj[k]);
} else if (Array.isArray(obj[k])) {
const newName = updateKey(obj, k);
obj[newName].forEach(el => {
changeName(el);
});
} else {
const newName = updateKey(obj, k);
}
}
}
console.log("finish", JSON.stringify(obj, null, 2));
fs.writeFileSync(`export/export.json`, JSON.stringify(obj, null, 2));
});