如何修改嵌套对象数组中的键名:替换name为title、Email为subtitle
问题需求
- 将嵌套对象数组中每个对象的
name键替换为title - 将每个对象
attributes属性下的Email键替换为subtitle
原数组示例
const originalArray = [ { name: "User 1", attributes: { Age: 25, Email: "user1@example.com" }, otherKey: "value1" }, { name: "User 2", attributes: { Age: 30, Email: "user2@example.com" }, otherKey: "value2" } ];
常见错误尝试(示例)
// 仅处理了外层name,未处理嵌套的Email,且直接修改原对象 const wrongResult = originalArray.map(item => { item.title = item.name; delete item.name; return item; });
期望输出
const expectedArray = [ { title: "User 1", attributes: { Age: 25, subtitle: "user1@example.com" }, otherKey: "value1" }, { title: "User 2", attributes: { Age: 30, subtitle: "user2@example.com" }, otherKey: "value2" } ];
可行解决方案
方案1:纯函数式处理(不修改原数组)
const transformedArray = originalArray.map(item => { // 解构取出外层属性,保留剩余字段 const { name, attributes, ...restProps } = item; // 处理嵌套的attributes对象 const updatedAttributes = attributes ? { ...attributes, subtitle: attributes.Email } : {}; delete updatedAttributes.Email; // 返回新对象 return { title: name, attributes: updatedAttributes, ...restProps }; });
方案2:简洁遍历写法
const transformedArray = originalArray.map(({ name, attributes, ...rest }) => ({ title: name, attributes: attributes && Object.fromEntries( Object.entries(attributes).map(([key, val]) => key === 'Email' ? ['subtitle', val] : [key, val] ) ), ...rest }));
核心说明
- 使用
map遍历数组,返回全新对象,避免污染原数组(若不需要保留原数组,也可直接修改,但纯函数写法更安全) - 外层通过解构赋值分离需要修改的字段与其他字段,保留原有结构
- 内层处理
attributes时,要么通过对象展开+删除旧键的方式替换,要么通过Object.entries遍历键值对直接替换键名
内容的提问来源于stack exchange,提问作者Allu Manikyam
相关产品推荐
相关产品推荐

