abdolence / x2js

x2js - XML to JSON and back for JavaScript
1.01k stars 492 forks source link

Working with arrays in recursive models #70

Open mellis481 opened 6 years ago

mellis481 commented 6 years ago

Functionality exists to specify the path to arrays in your model in the X2JS options. This prevents an array with a single item from being serialized as an object instead of an array. Code-wise, this is accomplished with the following where Items is an array in MyXml:

 var x2js = new X2JS({
        arrayAccessFormPaths : [
           "MyXml.Items"
        ]
    });

How this is accomplished with a recursive model, though? Using Typescript to give an example:

interface MyEntity {
    id: string;
    name: string;
    children: MyEntity[];
}

In this example, you would have potentially unlimited arrayAccessFormPaths values to account for all the levels of children in MyEntity. Eg.

 var x2js = new X2JS({
        arrayAccessFormPaths : [
           "MyEntity.children",
           "MyEntity.children.children",
           "MyEntity.children.children.children",
           "MyEntity.children.children.children.children",
           "MyEntity.children.children.children.children.children",
           ...
        ]
    });
mellis481 commented 6 years ago

I also attempted to use regex arrayAccessFormPaths values, but it does not seem to process them correctly.