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
我知道有一些类似的问题,但不是真的喜欢这个。
这样做的优雅方式是什么?
答案 0 :(得分:1)
好吧,您可以拆分字符串,循环以创建所需的数据结构 - 请参阅下面的演示:
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;}
答案 1 :(得分:1)
您可以先使用for...in
循环循环对象,然后在.
拆分每个键,并使用reduce来构建对象。
var input = {
"id": 'AD101',
"specified.name": 'BRYH',
"specified.manufacturer": 'some manufacturer',
"specified.environment.state": 'good'
}
var result = {}
for (var k in input) {
k.split('.').reduce(function(r, e, i, arr) {
return r[e] || (r[e] = arr[i + 1] ? {} : input[k])
}, result)
}
console.log(result)