方法中用到 lodash.js 的一个 merge合并对象方法
let arr = [
{
name:'a[0].b.c',
value:123
},{
name:'a[0].b.a',
value:123
},{
name:'a[1].a.a',
value:456
},{
name:'c.d.a',
value:789
},{
name:'b.c.c[0]',
value:789
},{
name:'b.a[1].c',
value:789
},{
name:'b.a[1].d',
value:456
},{
name:'b.a[0].c',
value:789
}
]
let obj = {}
arr.forEach(e=>{
let a = `${e.name}`.split('.');
let b = a[0].includes('[')?[]:{};
if(a[0].includes('[')){
let t = a[0].match(/\[(\S*)]/)[1];
let t1 = a[0].match(/(\S*)\[/)[1];
if(!obj.hasOwnProperty(t1)) obj[t1] = [];
if(!obj[t1][t]){
obj[t1][t] = getObj(a,b,e)
}else{
obj[t1][t] = _.merge(obj[t1][t],getObj(a,b,e))
}
}else{
if(!obj.hasOwnProperty(a[0])){
obj[a[0]] = getObj(a,b,e)
}else{
obj[a[0]] = _.merge(obj[a[0]],getObj(a,b,e))
}
}
});
function getObj(arr,type,e){
return arr.reduceRight((p,c,i)=>{
if(!i) return p
if(c.includes('[')){
let t = c.match(/\[(\S*)]/)[1];
let t1 = c.match(/(\S*)\[/)[1];
let ta = Array(t+1).fill()
ta[t] = ((arr.length - 1)==i)? e.value:p
return {[t1]:ta}
}else{
if((arr.length - 1)==i) return {[c]:e.value}
return {[c]:p}
}
},type);
}
console.log(obj)