如何在JavaScript中通过函数动态获取JSON对象的嵌套字段值?
首先得先修正你写的JSON对象语法,里面缺少了几个逗号,不然会报错,修正后是这样:
let myJson = { 'name':'John Doe', 'address': { 'country':'CN', 'city':'Toronto' } }
接下来给你几种扩展getValue函数的方法,用来获取嵌套字段的值:
方法1:接受点分隔的路径字符串
把嵌套路径写成类似'address.country'的形式,函数内部把字符串按.分割成数组,逐层遍历对象取值:
function getValue(path) { let result = myJson; const keys = path.split('.'); for (const key of keys) { // 路径不存在时返回undefined if (!result || !(key in result)) { return undefined; } result = result[key]; } console.log(result); return result; } // 调用示例 getValue('name'); // 输出 John Doe getValue('address.country'); // 输出 CN getValue('address.city'); // 输出 Toronto
方法2:接受数组形式的路径
如果你的键名里可能包含小数点(比如某个键叫'user.info'),用数组传路径更稳妥:
function getValue(keys) { let result = myJson; for (const key of keys) { if (!result || !(key in result)) { return undefined; } result = result[key]; } console.log(result); return result; } // 调用示例 getValue(['name']); // 输出 John Doe getValue(['address', 'country']); // 输出 CN
进阶:支持默认值
可以给函数加个默认值参数,当路径不存在时返回预设值:
function getValue(path, defaultValue) { let result = myJson; const keys = typeof path === 'string' ? path.split('.') : path; for (const key of keys) { if (!result || !(key in result)) { console.log(defaultValue); return defaultValue; } result = result[key]; } console.log(result); return result; } // 调用示例 getValue('address.age', '未知'); // 输出 未知
内容的提问来源于stack exchange,提问作者askwer
相关产品推荐
相关产品推荐

