You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从变量计算数组成员触发TypeError,求解决及数组构建方案

解决TypeError并构建计算对象数组的方案

我来帮你搞定这个问题!先理清你遇到的错误原因,再一步步实现你的最终目标。

为什么会出现TypeError: myData.foo.$ is not a function?

你写的myData.foo.$(myData.thud)是想调用foo对象里的$方法,但JSON格式只能存储字符串、数字、对象、数组这些静态数据,不能保存函数。你的JSON里根本没有定义$这个方法,JavaScript自然会报错说它不是一个函数。

你真正想要的是用myData.thud的值(也就是"bar")作为键,去访问myData.foo对应的属性,这时候应该用方括号语法来实现。

修正后的测试代码

把你的代码改成下面这样,就能正确输出baz了:

// 获取JSON数据并转换为对象
let myFile = '{"foo": {"bar": "baz"}, "thud": "bar"}';
let myData = JSON.parse(myFile);

// 用方括号语法通过变量访问属性,正确返回"baz"
console.log(myData.foo[myData.thud]);

实现包含计算对象的数组

接下来咱们看看怎么构建包含一个或多个这类计算对象的数组。假设你有多个数据源,或者需要从现有数据生成计算后的对象,这里给你一个示例:

// 模拟多个JSON数据源
const dataSources = [
  '{"foo": {"bar": "baz"}, "thud": "bar"}',
  '{"foo": {"apple": "red"}, "thud": "apple"}',
  '{"foo": {"car": "blue"}, "thud": "car"}'
];

// 遍历数据源,生成包含计算对象的数组
const computedArray = dataSources.map(source => {
  const parsedData = JSON.parse(source);
  // 这里可以根据需求自定义计算后的对象结构
  return {
    targetKey: parsedData.thud,
    targetValue: parsedData.foo[parsedData.thud],
    rawData: parsedData // 可选:保留原始数据
  };
});

// 打印结果
console.log(computedArray);

运行这段代码后,你会得到一个数组,每个元素都是从原始JSON计算得到的对象:

[
  { targetKey: 'bar', targetValue: 'baz', rawData: { foo: { bar: 'baz' }, thud: 'bar' } },
  { targetKey: 'apple', targetValue: 'red', rawData: { foo: { apple: 'red' }, thud: 'apple' } },
  { targetKey: 'car', targetValue: 'blue', rawData: { foo: { car: 'blue' }, thud: 'car' } }
]

你可以根据自己的实际需求调整计算对象的结构,比如只保留需要的属性,或者添加更多计算逻辑。

内容的提问来源于stack exchange,提问作者Jason Berryman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:08:15