function stringToObject(str) { try { const obj = JSON.parse(str); if (typeof obj === 'object' && obj !== null) { return obj; } else { return false; } } catch (error) { return false; } }

console.log(stringToObject('{ 'name': 'John', 'age': 30, 'city': 'New York' }')); // { name: 'John', age: 30, city: 'New York' } console.log(stringToObject('not an object')); // false

function objectToObject(obj) { if (typeof obj === 'object' && obj !== null) { return obj; } else { return false; } }

console.log(objectToObject({ name: 'John', age: 30, city: 'New York' })); // { name: 'John', age: 30, city: 'New York' } console.log(objectToObject('not an object')); // false

TypeScript 函数:将字符串或对象转换为对象

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

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