我想將不同的 json 結構更改為平面結構,以便在 html 上輕松呈現。所以我在資料內部有 n 個嵌套,有時我得到鍵和值,有時只是值。有什么簡單的方法可以做到嗎?
這是我擁有的一些 json 示例:
{
"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": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
這是我想要得到的東西
"glossary": {
"title": "example glossary",
"GlossDivTitle": "S",
"GlossDivGlossListGlossEntryID": "SGML",
"GlossDivGlossListGlossEntrySortAs": "SGML",
"GlossDivGlossListGlossEntryGlossTerm": "Standard Generalized Markup Language",
"GlossDivGlossListGlossEntryAcronym": "SGML",
"GlossDivGlossListGlossEntryAbbrev": "ISO 8879:1986",
"GlossDivGlossListGlossEntryGlossDefPara": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossDivGlossListGlossEntryGlossDefGlossSeeAlso": "GML, XML",
"GlossDivGlossListGlossEntryGlossSee": "markup",
}
我正在使用 sencha js,想法是在 html 中呈現任何型別的 json,就像這樣。
tpl: new Ext.XTemplate(
'<table border="1" cellpadding="10" cellspacing="0">',
'<tpl foreach=".">',
'<tr>',
'<td>{$}</td>',
'<td>{.}</td>',
'</tr>',
'</tpl>',
'</table>'
, {
complied: true
}
)
uj5u.com熱心網友回復:
遞回是一個解決方案:
更新:
const flattenedKeys = (json) => {
// Container for the keys
const flattenedObj = {};
const traverse = (obj, currentPath = '') => {
// Traverse all the properties
Object.entries(obj).forEach(([key, value]) => {
const newPath = currentPath key;
// If obj[key] is an array
if (Array.isArray(value)) {
value.forEach(item => {
traverse(item, newPath)
});
return;
}
// If obj[key] traverse recursively nested properties
if (typeof value === 'object') return traverse(value, newPath);
// If obj[key] is not an object or an array
flattenedObj[newPath] = value;
});
}
// Traverse recursively the whole object
traverse(json);
return flattenedObj;
}
uj5u.com熱心網友回復:
如果要展平物件,則需要執行遞回回圈
下面是一個簡單的示例,只是為了說明它是如何作業的,它不使用遞回。
// You data to be flatten
var obj = { ... }
var data = {}
Object.keys(obj).forEach(function (item) {
// Check for value type of object
if(typeof obj[item] == 'object') {
// Check if array
if(Array.isArray(obj[item])) {
// Append the value
data[item] = obj[item];
} else {
// Must loop to this object
// You can recursive function
var nestObj = obj[item];
Object.keys(nestObj).forEach(nest => {
// Append to the data
// This time with nested object,
// We have to merge the parents key and the nested key
data[item nest] = nestObj[nest]
})
}
} else {
// Append non object values
data[item] = obj[item];
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/341041.html
標籤:javascript 数组 json extjs
上一篇:如何將經典JavaScript中的“forof”轉換為jQuery?
下一篇:用JS迭代DOM屬性x次
