【发布时间】:2019-03-07 19:33:59
【问题描述】:
我是一个表的结果,它为我提供了我需要用来创建 JSON 对象的字段的动态层次结构。
前:
[ [ 'request', 'cycleRange' ],
[ 'request', 'cycleRange', 'from' ],
[ 'request', 'cycleRange', 'to' ],
[ 'request', 'cycleRange', 'to', 'month' ],
[ 'request', 'cycleRange', 'to', 'year' ],
[ 'request', 'datestmt' ],
[ 'request', 'singleTran' ],
[ 'request', 'singleTran', 'datePost' ],
[ 'request', 'singleTran', 'dateTo' ] ]
我希望使用此示例创建的 JSON 对象应该是:
let expected = {
request: {
cycleRange: {
from: null,
to: {
month: null,
year: null
}
},
datestmt: null,
singleTran: {
datePost: null,
dateTo: null
}
}
};
我正在使用这个函数来尝试构建对象,但我只得到最终的数组作为对象:
let final = {};
for (let i of heirarchy) {
assign(final, i, null);
}
function assign(obj, keyPath, value) {
let lastKeyIndex = keyPath.length - 1;
let key;
let i;
for (i=0; i<lastKeyIndex; i++) {
key = keyPath[i];
if (!(key in obj)) {
obj[key] = {};
} else {
if (i !== lastKeyIndex) {
obj[key] = {};
}
}
obj = obj[key];
}
obj[keyPath[lastKeyIndex]] = value;
}
目前我只得到结果:(我的源层次结构的最后一个索引)
{"request":{"singleTran":{"dateTo":null}}}
任何帮助将不胜感激。
【问题讨论】: