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

如何使用JavaScript在指定JSON结构中新增数组块

Solution to Add Dynamic Block to JSON Object

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 myBlock as the new key in the objs object.
  • The value we assign matches the exact array structure used by your existing blocks.

内容的提问来源于stack exchange,提问作者Supreme Gang Certified Member

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 11:32:41