侃侃无极
const input = { 0: { c: 1, d: 2, e: { a: 3, b: 4 } }};const mapObj = (obj, map) => Object.fromEntries(Object.entries(obj).map(([k, v]) => ([k, map(v)])));const result = mapObj(input, ({ c, d, e }) => ({ e: { c, d, ...e }}));console.log(result);您可以使用对象解构来获取对象,然后组合新对象。
智慧大石
对于完整的动态方法,您可以查找属性作为对象并收集键,如果不收集对象中的属性,以便稍后将这些属性分配给单个嵌套对象。如有必要,如果找到多个嵌套属性,则迭代嵌套属性。function refine(object) { var temp = {}, target = [], remove = []; Object.entries(object).forEach(([k, v]) => { if (v && typeof v === 'object') { target.push(k); return; } temp[k] = v; remove.push(k); }); if (target.length === 1) { Object.assign(object[target[0]], temp); remove.forEach(k => delete object[k]); } target.forEach(k => refine(object[k]));}var data = { 0: { c: 1, d: 2, e: { a: 3, b: 4} }, 1: { c: 5, d: 6, e: { a: 7, b: 8 } } };refine(data);console.log(data);