我正在尝试将多级JSON对象展平为简单输出。
key2:{
keyB1:{
keyC1:{
keyD1:'value b c 1'
}
},
keyB2:{
keyC2:'value b c 2'
}
}
我的输出在第一次迭代中很好,但是第二次没有设置计数器。请运行代码以查看问题。
function flattenInput(datainput) {
const result = {};
const callit1 = function(keylist, datainput) {
for (i in datainput) {
keylist = keylist + '.' + i;
if (typeof datainput[i] === 'object') {
return callit1(keylist, datainput[i]);
} else {
return keylist;
}
}
}
let klist = '';
for (i in datainput) {
if (typeof datainput[i] === 'object') {
klist = callit1(i, datainput[i]);
console.log(klist);
}
}
console.log(result);
}
flattenInput(input);
key2.keyB1.keyC1.keyD1:'值b c 1'
key2.keyB2.keyC2:'值b c 2'
key2.keyB1.keyC1.keyD1:'值b c 1' (仅)
答案 0 :(得分:1)
您可以使用递归来更深入地浏览键,并使用键数组来跟踪已访问的键。
这是假设最深的对象是字符串。
let obj = { key2: { keyB1: { keyC1: { keyD1: 'value b c 1' } }, keyB2: { keyC2: 'value b c 2' } } };
function downstream(desiredObj, currentObj, keys) {
if (typeof currentObj === 'string') {
desiredObj[keys.join('.')] = currentObj;
} else {
Object.keys(currentObj).forEach(key => downstream(desiredObj, currentObj[key], [...keys, key]));
}
}
let result = {};
Object.keys(obj).forEach(key => downstream(result, obj[key], [key]));
console.log(result);