kwhitley / treeize

Converts row data (in JSON/associative array format) to tree structure based on column naming conventions.
MIT License
189 stars 24 forks source link

Unable to obtain homogeneous compound object array #45

Open rapodaca opened 6 years ago

rapodaca commented 6 years ago

I'd like to use Treeize (2.1.2) to make an array of homogeneous compound objects.

A simple example would be a product with many pricings. Each pricing is composed of a price and a segment. The latter two are in turn compound objects.

Here's my input:

    let Treeize = require('treeize');
    let tree = new Treeize();
    let data = [
      {
        product_id: 1,
        'pricings:price:value': 10,
        'pricings:price:currency': 'USD',
        'pricings:segment:id': 1,
        'pricings:segment:name': 'Guest'
      },
      {
        product_id: 1,
        'pricings:price:value': 20,
        'pricings:price:currency': 'USD',
        'pricings:segment:id': 2,
        'pricings:segment:name': 'Preferred'
      }
    ];

    tree = tree.grow(data);

However, running this example produces:

[
  {
    "product_id": 1,
    "pricings": [
      {
        "segment": {
          "id": 1,
          "name": "Guest"
        }
      },
      {
        "price": {
          "value": 10,
          "currency": "USD"
        }
      },
      {
        "segment": {
          "id": 2,
          "name": "Preferred"
        }
      },
      {
        "price": {
          "value": 20,
          "currency": "USD"
        }
      }
    ]
  }
]

Segment and price are independent objects, and the array is heterogeneous. This isn't what I expected.

I can get the expected behavior by adding a dummy simple value to each pricing:

    let Treeize = require('treeize');
    let tree = new Treeize();
    let data = [
      {
        product_id: 1,
        'pricings:dummy': 1,
        'pricings:price:value': 10,
        'pricings:price:currency': 'USD',
        'pricings:segment:id': 1,
        'pricings:segment:name': 'Guest'
      },
      {
        product_id: 1,
        'pricings:dummy': 2,
        'pricings:price:value': 20,
        'pricings:price:currency': 'USD',
        'pricings:segment:id': 2,
        'pricings:segment:name': 'Preferred'
      }
    ];

    tree = tree.grow(data);

which yields:

[
  {
    "product_id": 1,
    "pricings": [
      {
        "dummy": 1,
        "segment": {
          "id": 1,
          "name": "Guest"
        },
        "price": {
          "value": 10,
          "currency": "USD"
        }
      },
      {
        "dummy": 2,
        "segment": {
          "id": 2,
          "name": "Preferred"
        },
        "price": {
          "value": 20,
          "currency": "USD"
        }
      }
    ]
  }
]

Is what I'm seeing expected behavior, and if so, is there a way to override it?