JavaScript动态属性赋值报错:如何为onedata.Networks_keys正确赋值?
Hey there! That syntax error is popping up because you can't use an expression like onedata[test]+'_keys' directly on the left side of an assignment in JavaScript. Let's break down how to fix this properly.
The Issue
When you try to write onedata[test]+'_keys' = "", JavaScript doesn't recognize this as a valid way to target an object property. The left side of an assignment needs to be a reference to a property, not a string concatenation result.
The Solution
You need to first compute the full property name (combining test's value with _keys), then use bracket notation to assign the empty string to that property. There are two clean ways to do this:
1. Use a variable to store the computed key name
This is great for readability, especially if you need to reuse the key later:
const test = "Networks"; let onedata = JSON.parse(read_data); // Compute the full property name const targetKey = `${test}_keys`; // Assign the empty string using bracket notation onedata[targetKey] = "";
2. Directly compute the key in the bracket notation
If you don't need to reuse the key, you can do it in one line with template literals:
const test = "Networks"; let onedata = JSON.parse(read_data); // Combine the variable and suffix directly inside the brackets onedata[`${test}_keys`] = "";
Why This Works
Bracket notation (object[key]) in JavaScript allows you to use dynamically calculated strings as property names, which is exactly what you need here. Unlike dot notation (e.g., object.Networks_keys), which only works with fixed, hardcoded property names, bracket notation lets you build the name on the fly.
内容的提问来源于stack exchange,提问作者Mia

