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

如何在filter函数中正确使用变量访问JSON属性?

如何在filter函数中正确使用变量访问JSON属性?

Hey there, I see exactly what's causing your error! Let's break down the problem and fix it step by step.

The Root Issue

When you write json.VARIABLE_NAME in your code, JavaScript is literally looking for a property named "VARIABLE_NAME" on your json object—not using the value stored in your VARIABLE_NAME variable. Since there's no property with that exact literal name, you get the "undefined" error when trying to call .filter() on it.

Plus, your variable assignment has a small mistake: if test is the name of the JSON property you want to target, it needs to be wrapped in quotes (otherwise JavaScript will treat it as an undefined variable named test).

Fixed Code Example

Here's how to adjust your code to work correctly:

// First, assign the property name as a string to your variable
const VARIABLE_NAME = 'test'; 

// Use bracket notation instead of dot notation to access the dynamic property
const results = json[VARIABLE_NAME].filter((result) => {
  // Your filter logic goes here, e.g.:
  // return result.status === 'success';
});

Why This Works

  • Bracket notation (obj[variable]) lets you use a variable to dynamically reference an object property. This is exactly what you need when you don't know the property name ahead of time.
  • Dot notation (obj.property) only works with literal property names (like json.test), not variables.

Bonus: Add Error Handling

To avoid crashes if the property doesn't exist or isn't an array, you can add a quick check:

const VARIABLE_NAME = 'test';

if (json[VARIABLE_NAME] && Array.isArray(json[VARIABLE_NAME])) {
  const results = json[VARIABLE_NAME].filter((result) => {
    // Your filter logic
  });
} else {
  console.log(`Warning: Property "${VARIABLE_NAME}" doesn't exist or isn't an array`);
}

Key Takeaway

Whenever you need to access an object property using a variable, always use bracket notation instead of dot notation. That's the core fix here!

备注:内容来源于stack exchange,提问作者dawphin777

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.21 15:19:35