可以使用JavaScript的typeof运算符来确定值的类型,并使用递归来遍历对象。
示例代码如下:
function pickValues(obj) { const result = {};
for (const key in obj) { if (obj.hasOwnProperty(key)) { const val = obj[key]; switch (typeof val) { case "object": result[key] = pickValues(val); break; case "string": result[key] = val.trim(); break; case "number": result[key] = parseFloat(val); break; case "boolean": result[key] = val === "true"; break; default: result[key] = val; } } }
return result; }
const obj = { name: " John Doe ", age: "30", subObj: { prop: " some value ", num: "42", bool: "true" } };
const picked = pickValues(obj);
console.log(picked);
// 输出结果: // { // name: "John Doe", // age: 30, // subObj: { // prop: "some value", // num: 42, // bool: true // } // }