我正在尝试将'_x'
添加到每个对象键,并'_y'
添加到每个对象值。
这是代码:
var data = {
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": "GMLXML"
},
"GlossSee": "markup"
}
}
}
}
}
function treee(data) {
Object.keys(data).map( function (key) {
if(Object.keys(data[key]).length == 0){
data[key] = {[key + "_x"]: data[key] + "_y"};
}
else{
data[key] = { [key + "_x"]: treee(data[key]) };
}
});
}
它不起作用,我不知道为什么。你能告诉我什么错吗?
答案 0 :(得分:2)
基本上你需要新密钥而不是旧密钥并删除实际密钥。
另一部分是改变内部对象,如果必要的话。
function treee(data) {
Object.keys(data).map(function (key) {
if (data[key] && typeof data[key] === 'object') {
treee(data[key]);
}
data[key + '_x'] = typeof data[key] === 'string' ? data[key] + '_y' : data[key];
delete data[key];
});
}
var data = { glossary: { title: "example glossary", GlossDiv: { title: "S", GlossList: { GlossEntry: { ID: "SGML", SortAs: "SGML", GlossTerm: "Standard Generalized Markup Language", Acronym: "SGML", Abbrev: "ISO 8879:1986", GlossDef: { para: "A meta-markup language, used to create markup languages such as DocBook.", GlossSeeAlso: "GMLXML" }, GlossSee: "markup" } } } } };
treee(data);
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:2)
如果将对象转换为JSON,然后使用字符串替换:
,则更容易实现
var data = { "glossary": { "title": "example glossary", "GlossDiv": { "title": "S", "GlossList": { "GlossEntry": { "ID": "SGML", "SortAs": "SGML", "GlossTerm": "Standard Generalized Markup Language", "Acronym": "SGML", "Abbrev": "ISO 8879:1986", "GlossDef": { "para": "A meta-markup language, used to create markup languages such as DocBook.", "GlossSeeAlso": "GMLXML" }, "GlossSee": "markup" } } } } }
var jsonString = JSON.stringify(data),
replacedValues = jsonString
.replace(/([\w.])"/g, '$1_y"') // Add _y to all strings in there.
.replace(/_y":/g, '_x":') // Replace _y with _x for all keys.
newData = JSON.parse(replacedValues);
console.log(newData);
另一种选择是使用正则表达式来替换密钥,然后在解析JSON时使用reviver
函数来修改值:
var data = { "glossary": { "title": "example glossary", "GlossDiv": { "title": "S", "GlossList": { "GlossEntry": { "ID": "SGML", "SortAs": "SGML", "GlossTerm": "Standard Generalized Markup Language", "Acronym": "SGML", "Abbrev": "ISO 8879:1986", "GlossDef": { "para": "A meta-markup language, used to create markup languages such as DocBook.", "GlossSeeAlso": "GMLXML" }, "GlossSee": "markup" } } } } }
var jsonString = JSON.stringify(data)
.replace(/":/g, '_x":'); // Add _x to all keys.
var newData = JSON.parse(jsonString, function(key, val){
if(typeof val === 'string') // For every value, if the value is a string
return val + '_y'; // Add `_y`
return val; // Otherwise, just return the value.
});
console.log(newData);