function toObject(data) { if (typeof data === 'string') { try { return JSON.parse(data); } catch (error) { return {}; } } else if (typeof data === 'object') { return data; } else { return {}; } }

// 示例 const str = '{"name": "Tom", "age": 18}'; const obj = {name: 'Jerry', age: 21}; console.log(toObject(str)); // {name: "Tom", age: 18} console.log(toObject(obj)); // {name: "Jerry", age: 21} console.log(toObject('abc')); // {}

ts写一个函数传入数据是字符串或者json将他们都转为对象

原文地址: https://www.cveoy.top/t/topic/gImz 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录