我无法解决这个问题。
我有一个看起来像这样的设置对象
const setting = [
{
Key: 'root/',
Value: null,
},
{
Key: 'root/second-root/',
Value: null,
},
{
Key: 'root/second-root/names/',
Value: null,
},
{
Key: 'root/second-root/names/capital-letter',
Value: true,
},
{
Key: 'root/second-root/countries/',
Value: null,
},
{
Key: 'root/second-root/countries/enabledcountries',
Value: 'US,UK,DK',
},
{
Key: 'root/second-root/countries/async',
Value: 'true',
},
{
Key: 'root/second-root/countries/manual',
Value: 'true',
},
{
Key: 'root/second-root/countries/limit',
Value: '4200',
},
{
Key: 'root/second-root/names/onyl-last-name',
Value: false,
},
];
我需要将其转换为看起来像
const wantedResult = [
{
'root': {
'Value': null,
'second-root': {
'Value': null,
'names': {
'Value': null,
'capital-letter': {
'Value': true,
}
'onyl-last-name': {
'Value': false,
}
},
'countries': {
'Value': null,
'enabledcountries': {
Value: 'US,UK,DK',
},
'async': {
Value: 'true',
},
'manual': {
Value: 'true',
},
'limit': {
Value: '4200',
}
}
}
}
}
];
它是控制层次结构的 Key 属性。如果它以/结尾,则该项目是一个目录,否则它是一个值。
问题是扁平结构不必以正确的顺序返回项目。就像示例中一样,最后一项是 'root/second-root/names/onyl-last-name',
即使名称层次结构位于平面结构的开头。
我尝试过一种 array.reduce 形式,但每次都会卡住。有人可以帮助我吗?
最佳答案
您可以迭代数组并获取不带最后一个斜杠的值,并将其拆分为对象的路径以分配值。
如有必要,将结果放入数组中。
在forEach
中有效
a destructuring
assignment从对象中获取键和值,用空字符串查找字符串末尾的斜杠的替换,
用斜杠分割字符串,它返回一个包含不带斜杠的字符串的数组,
使用
Array#reduce
将结果对象作为累加器。它内部使用带有 logical OR
||
的默认模式。检查左侧是否是 truthy值,如果没有,则分配一个对象。返回该值用于与下一个键进行检查。在迭代结束时,它会重新调整对象引用,然后分配值。
var setting = [{ Key: 'root/', Value: null }, { Key: 'root/second-root/', Value: null }, { Key: 'root/second-root/names/', Value: null }, { Key: 'root/second-root/names/capital-letter', Value: true }, { Key: 'root/second-root/countries/', Value: null }, { Key: 'root/second-root/countries/enabledcountries', Value: 'US,UK,DK' }, { Key: 'root/second-root/countries/async', Value: 'true' }, { Key: 'root/second-root/countries/manual', Value: 'true' }, { Key: 'root/second-root/countries/limit', Value: '4200' }, { Key: 'root/second-root/names/onyl-last-name', Value: false }],
result = {};
setting.forEach(({ Key, Value }) => Key
.replace(/\/$/, '')
.split('/')
.reduce((o, k) => o[k] = o[k] || {}, result).Value = Value
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 将平面 json 结构转换为分层结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48190720/