netnr 2024-12-08

原始数据

const nestedData = [
  {
    id: 1, name: "Item 1",
    subModel: { title: "Title 1", content: "Content 1" }
  },
  {
    id: 2, name: "Item 2", 
    subModel: { title: "Title 2", content: "Content 2" }
  }
];

目标数据

将对象 subModel 展开到顶层,同时保留其它属性

转换后希望的格式

[
  {
    id: 1, name: "Item 1", title: "Title 1", content: "Content 1"
  },
  {
    id: 2, name: "Item 2", title: "Title 2", content: "Content 2"
  }
]

转换

解构赋值和对象展开运算符

const newData = nestedData.map(({ subModel, ...rest }) => ({ ...rest, ...subModel }));

({ subModel, ...rest }) 从当前元素中解构出 subModel 属性,并将剩余的属性放入 rest 对象中

({ ...rest, ...subModel }) 创建一个新的对象,将 rest 对象中的属性和 subModel 对象中的属性合并到一起。

封装方法

function flattenData(data, key) {
    return data.map(item => {
        const { [key]: nestedObject, ...rest } = item;
        return { ...rest, ...nestedObject };
    });
}

// 调用,传入原始数组和需要展开的 key
console.debug("flattenData", flattenData(nestedData, "subModel"));

ref https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

登录写评论