如何使用JavaScript在指定JSON结构中新增数组块
Hey there, let's get this sorted for you! The key here is using JavaScript's dynamic object property access to add your new block without altering the existing structure. Here's a step-by-step breakdown:
Step 1: Parse the JSON (if it's a string)
First, if your original data is a JSON string, you'll need to convert it into a JavaScript object so you can modify it:
// Your original JSON string const originalJsonStr = '{ "objs": { "block": [ {"long": "value1"} ], "block1": [ {"long": "value2"} ], "nameofblock": [ {"long": "thisisthevalueoflonginjson"} ] } }'; // Parse it to a JS object const dataObj = JSON.parse(originalJsonStr);
If your data is already a JavaScript object (not a string), you can skip this step and use that object directly.
Step 2: Add the New Block Using Your Variables
Use square bracket notation ([]) to dynamically set the property name from your myBlock variable, then assign the required array structure:
let myBlock = "name_of_block"; let longData = "data_inside_the_block"; // Add the new block to the "objs" object dataObj.objs[myBlock] = [{ long: longData }];
This works because square bracket syntax lets you use variables as property names, which is perfect for your use case. It won't touch any existing properties in the objs object.
Step 3: Convert Back to JSON (if needed)
If you need the updated data as a JSON string again, use JSON.stringify:
const updatedJsonStr = JSON.stringify(dataObj, null, 2); console.log(updatedJsonStr);
Running this will output exactly the structure you're looking for:
{ "objs": { "block": [ { "long": "value1" } ], "block1": [ { "long": "value2" } ], "nameofblock": [ { "long": "thisisthevalueoflonginjson" } ], "name_of_block": [ { "long": "data_inside_the_block" } ] } }
Why This Works
- We're modifying the JavaScript object directly, which preserves all existing properties.
- Dynamic property access with square brackets lets us use the value of
myBlockas the new key in theobjsobject. - The value we assign matches the exact array structure used by your existing blocks.
内容的提问来源于stack exchange,提问作者Supreme Gang Certified Member

