如何创建嵌套JSON数组?需构建指定TableComponent JSON结构
Alright, let's break this down based on your target JSON structure and existing code. You want to end up with a TableComponent that matches this structure:
{ "Value": { "abc": {"text": "password"} }, "Name": "id", "Hidden": "0", "ReadOnly": "0", "Type": "STRING" }
And you're working with initial code that has a TableComponent with elements and Components arrays, plus a property object you want to integrate. Here are two practical approaches, plus a structural recommendation:
Option 1: Embed property Directly in an elements Item
If you want to keep your existing elements array structure (for storing multiple component instances or positional data), you can add the property object as a field inside each element you push to the array. This works well if each element needs its own set of properties:
var TableComponent = { elements: [], Components: [] }; var property = { prop: [] }; // Add property as a nested field in the new element TableComponent.elements.push({ "id": a.id, "abs_x": a.abs_x, "abs_y": a.abs_y, "property": property });
Option 2: Align Structure with Your Target JSON
If your end goal is to match the specific TableComponent structure you outlined, you'll want to refactor the initial code to map to that hierarchy. You can integrate elements and property into the Value object (since that's where dynamic data lives in your target):
// Start with your target structure as the base var TableComponent = { "Value": {}, "Name": "id", "Hidden": "0", "ReadOnly": "0", "Type": "STRING" }; var property = { prop: [] }; // Integrate elements and property into the Value field TableComponent.Value["abc"] = { "text": "password", "elements": [ { "id": a.id, "abs_x": a.abs_x, "abs_y": a.abs_y } ], "property": property };
Recommended Structural Adjustment
For long-term maintainability, if you plan to have multiple table components (or multiple fields within a single component), consider restructuring to group all related properties per component. This makes it easier to iterate over components and access their data:
var TableComponent = { components: [ // Renamed for clearer semantics { "Value": { "abc": {"text": "password"} }, "Name": "id", "Hidden": "0", "ReadOnly": "0", "Type": "STRING", "position": { "id": a.id, "abs_x": a.abs_x, "abs_y": a.abs_y }, // Group positional data "property": { prop: [] } } ] };
This structure keeps all relevant data for a single component grouped together, avoiding scattered arrays that can be hard to trace.
内容的提问来源于stack exchange,提问作者Neha rawat

