如何在JavaScript中使用变量作为键名读取JSON返回数据
实现方法
JavaScript 中访问对象属性有两种语法:
- 点语法:只能使用固定的属性名,不支持传入变量
- 方括号语法:支持传入字符串/变量作为属性名,刚好匹配你的需求
你只需要把~的位置替换为方括号包裹的inputdata变量即可:
const inputdata = document.getElementById('myinput').value fetch("https://jsonplaceholder.typicode.com/posts") .then((value) => value.json()) .then((json) => { // 方括号内会读取inputdata变量的值作为属性名 console.log(json[inputdata]) });
额外注意事项
你调用的接口返回结果是帖子数组,本身只有数组自带的属性(比如length),每个数组元素才拥有userId、id、title、body这些业务属性。如果你的需求是读取数组中某一项的对应属性,可以加可选链和空值兼容处理,避免属性不存在时报错:
const inputdata = document.getElementById('myinput').value fetch("https://jsonplaceholder.typicode.com/posts") .then((value) => value.json()) .then((json) => { // 示例:读取第一个帖子的对应属性,属性不存在时返回提示 console.log(json[0]?.[inputdata] ?? '查询的属性不存在') });
内容的提问来源于stack exchange,提问作者Daksh Verma
相关产品推荐
相关产品推荐

