我有以下对象
let demo = {a:'b', c:{0:{id:'one'},1:{id:'two'}}, d:{0:{country: {0:{name:'mx'},1:{name:'usa'}} }} };
键(例如(0,1))已集成到一个数组中,如下所示:
let result = {a:'b', c:[{id:'one'},{id:'two'}], d:[{country:[{name:'mx'},{name:'usa'}] }] };
有什么想法吗?
答案 0 :(得分:1)
您可以将对象reduce递归Object.values()
,然后使用http://127.0.0.1:9090将每个具有键0
的对象转换为数组:
const demo = {a:'b', c:{0:{id:'one'},1:{id:'two'}}, d:{0:{country: {0:{name:'mx'},1:{name:'usa'}} }} };
const arrayfy = (o) => Object.entries(o)
.reduce((r, [k, v]) => {
if(typeof v === 'object') {
const t = arrayfy(v);
r[k] = '0' in v ? Object.values(t) : arrayfy(t);
} else {
r[k] = v;
}
return r;
}, {});
const result = arrayfy(demo);
console.log(result);