1捅厂、獲取 JSON data 每一層的數(shù)據(jù)等太,并計(jì)算JSON 的最大層數(shù)
function run(obj) {
let ans = 0;
let data = [];
function fn(obj, level = 0) {
if (typeof obj === 'object') {
for (let k in obj) {
if (obj.hasOwnProperty(k) && typeof obj[k] === 'object') {
data.push({v: obj[k], h: level, key: k})
fn(obj[k], level + 1);
} else {
ans = Math.max(level + 1, ans);
data.push({v: obj[k], h: level, key: k})
}
}
}
}
fn(obj);
const map = data.reduce((ret, c, index) => {
if(ret[c.h] == null) {
ret[c.h] = [];
}
ret[c.h].push({k: c.key, v: c.v});
return ret;
}, {});
return {ans, map};
}
2探橱、測(cè)試邏輯
測(cè)試獲取每一層的數(shù)據(jù)
const ans = run(tests());
console.log('data is ', ans);
3申屹、附錄
測(cè)試數(shù)據(jù)
function tests() {
return {
a: { b: [1] },
c: {
d: {
e: {
f: 2, o: {
h: 3, i: [1, 2, 3], j: [
4, 5, 6,
[
{
k: 22,
l: 33,
m: [
{
x: 1,
y: 2,
z: 3
},
{
x: 4,
y: 5,
z: 6
}
]
}
]
]
}
}
}
},
}
}