我有以下JSON,其中“section”对象包含其他“section”对象和“items”。从这个对象,我需要提取“items”字段名称(所有父节的连接及其名称属性“)及其值。这样做的有效方法是什么?
请注意,以下内容只是我的json的一部分。部分和项目的嵌套级别是无限的。我需要递归地做一些事情。
JSON:
{
"section": [
{
"fieldId": "t1",
"name": "section-1",
"section": [
{
"fieldId": "t-1",
"name": "section2",
"and": [
{
"fieldId": null,
"items": [
{
"fieldId": "c-2",
"name": "item1",
"value": "123"
},
{
"fieldId": "c-3",
"name": "item2",
"value": "dsadsaddsa"
}
]
}
],
"section": []
}
]
}
]
}
Javascript我开始写作(不完整,我被困住):
function process(key,value) {
if (key == "section")
console.log(key + " : " + JSON.stringify(value[0]));
}
function traverse(o,func) {
for (var i in o) {
func.apply(this,[i,o[i]]);
if (typeof(o[i])=="object") {
traverse(o[i],func);
}
}
}
预期输出 一个javascript对象
{"section1-section2-item1":123, "section1-section2-item2":"dsadsaddsa"}
答案 0 :(得分:2)
以下是递归遍历函数的工作版本:
这是冗长的,但效率相当高。它确实对默认值进行了一些额外的遍历/工作 - 如果它是一个问题,也可以清理它们。
已更新,以便在处理时收集键/值解析并记录最终结果。
// This is just to help visualize the answer in the fiddle
function log(input) {
$('body').append($('<div>').text(input));
}
var finalObj = {};
function process(key,value) {
log(key + " : " + value);
// Collect in finalObj
finalObj[key] = value;
}
function traverse(section,func,path) {
var sectionIdx, andArr, andIdx, curAnd, items, itemIdx, curSection, curPath;
section = section || [];
path = path || [];
// Start with something in the path for this level
path.push('');
for(sectionIdx = 0; sectionIdx < section.length; ++sectionIdx) {
// Set reasonable defaults for current values
curSection = section[sectionIdx] || {};
andArr = curSection.and || [];
// Update the name if the section for this level in the hierarchy
path[path.length - 1] = curSection.name;
// Recurse into the current section
traverse(curSection.section, func, path);
// Remove the last part of the path from the previous recursion
path.length = path.length - 1;
// Current path as a string
curPath = path.join('-');
// Now iterate all the and objects
for(andIdx = 0; andIdx < andArr.length; ++andIdx) {
// Setup reasonable defaults for and and items
curAnd = andArr[andIdx] || {};
items = curAnd.items || [];
// Run through the items and process them with the full path
for(itemsIdx = 0; itemsIdx < items.length; ++itemsIdx) {
process(curPath + '-' + items[itemsIdx].name, items[itemsIdx].value);
}
}
}
}
traverse(jsonInput.section, process);
// Log out finalObj
log("Final Result:");
log(JSON.stringify(finalObj));
输出(基于提供的JSON中的当前name
属性):
section-1-section2-item1 : 123
section-1-section2-item2 : dsadsaddsa
Final Result:
{"section-1-section2-item1":"123","section-1-section2-item2":"dsadsaddsa"}
Updated fiddle ,避免在没有子节数组时的额外递归