dbankier / XMLTools-For-Appcelerator-Titanium

MIT License
64 stars 12 forks source link

Object vs array #9

Closed nuno closed 8 years ago

nuno commented 8 years ago

Hello David,

What should be the best approach to have something that allow one element to be output as an array or object? The code now automatically assigns a parent with one child as an object, but the same parent with more than one child as an array.

Thanks.

Examples

If the api back 2 items

<favorites>
        <item>
            <id>2241614</id>
        </item>
        <item>
            <id>2610611</id>
        </item>
    </favorites>
  "favorites": {
      "item": [
        { "id": "2241614" },
        { "id": "2610611" }
      ]
    }
If the api back JUST 1 item

<favorites>
        <item>
            <id>2241614</id>
        </item>
    </favorites>
    "favorites": {
      "item": { "id": "2241614" }
    }

Unfortunately this break our output in case if the api back 1 result.

dbankier commented 8 years ago

I use an arrayify function that turns the object into an array if it isn't one. I also use a oneOrMore function that applies the function argument to either the object or each object in the array if it is one..

nuno commented 8 years ago

May help others!

I had to deal with the situation in code, and add a check, if the results are exactly 1, then wrapper in array braces []


// "response.results" is from a callback, just a bit of context here.

var _myData = response.results.item;

  if (response.results.count === '1') {
     
      // If  return 1 item, then there is a need of wrapper in array braces
      _myData = [response.results.item];
}else{
       
      // More than 1 result is already an array
      _myData = response.results.item;
}
.......

If this is good practice, well not sure, but is the only way for now.