JavaScript中JSON数据处理:JSON.stringify+JSON.parse是否冗余?
问题分析与解答
报错原因拆解
- 直接调用
JSON.parse(notificationsData)报错:JSON.parse()仅能解析合法JSON字符串,但你传入的notificationsData是一个对象。当对象被直接传入该方法时,JS会自动将其转为字符串"[object Object]",这不属于有效JSON格式,因此抛出SyntaxError。 - 直接使用
notificationsData.map()报错:TypeScript提示'map' does not exist on type 'string',说明代码中notificationsData的类型标注为string,但实际运行时它是数组对象(从JSON.stringify输出数组格式可确认)。类型定义与实际值不匹配,导致TS编译报错。
当前写法是否冗余?
是冗余的。你用JSON.parse(JSON.stringify(notificationsData))是为了做深拷贝,但后续的map操作本身会生成全新数组,且回调中手动返回了新对象{ID: notification.ID, MESSAGE_TITLE: notification.MESSAGE_TITLE},完全不需要提前做深拷贝。这个步骤既浪费性能,也无实际作用。
优化后的代码
直接基于notificationsData操作即可,需先修正其类型定义(将类型从string改为Partial<Notification>[]或对应数组类型):
// 修正类型后直接操作 const Notifications: ActorNotification[] = (notificationsData as Partial<Notification>[]) .map((notification) => { return { ID: notification.ID, MESSAGE_TITLE: notification.MESSAGE_TITLE }; }) .sort((a, b) => new Date(b.CREATED_AT).getTime() - new Date(a.CREATED_AT).getTime());
若不想用类型断言,也可先做类型校验:
if (Array.isArray(notificationsData)) { const Notifications: ActorNotification[] = notificationsData .map((notification: Partial<Notification>) => { return { ID: notification.ID, MESSAGE_TITLE: notification.MESSAGE_TITLE }; }) .sort((a, b) => new Date(b.CREATED_AT).getTime() - new Date(a.CREATED_AT).getTime()); }
内容的提问来源于stack exchange,提问作者Julián Oviedo
相关产品推荐
相关产品推荐

