var input = {
"id": 'AB',
"specified.name": 'some name',
"specified.manufacturer": 'some manufacturer',
"specified.environment.state": 'good'
}
/**
var expectedOutput = {
id:'AB',
specified: {
name: 'some name',
manufacturer: 'some manufacturer',
environment: {
state: 'good'
}
}
};
**/
https://jsbin.com/senehijula/edit?html,js,output
我知道有一些类似的问题,但不是很喜欢这个问题。
有什么优雅的方法吗?
最佳答案
好了,您可以拆分字符串并循环遍历以创建所需的数据结构-请参见下面的演示:
var input = {
"id": 'AB',
"specified.name": 'some name',
"specified.manufacturer": 'some manufacturer',
"specified.environment.state": 'good'
}
var output = {};
Object.keys(input).forEach(function(e){
let keys = e.split('.');
let key = keys.pop();
let obj = keys.reduce(function(p,k){
p[k] = p[k] || Object.create(null);
return p[k];
}, output);
obj = obj || Object.create(null);
obj[key] = input[e];
});
console.log(output);
.as-console-wrapper{top:0;max-height:100%!important;}