Search code examples
javascriptxmlsoapnode-soap

node-soap force array when reponse field contains one child


When converting a field in XML in a response using node-soap, I would like to force a field to be an array even though it contains one child.

When there is only one child, a field is interpreted as an object. Please see an example below:

// Below gives {ArrayOfItems: {Item: { name: 'foo', ... }}
// But I'd like it to be {ArrayOfItems: {Item: [{name: 'foo', ... }]}
<ArrayOfItems>
  <Item>
    ...
  </Item>
</ArrayOfItems>

// Below gives  {ArrayOfItems: {Item: [{ name: 'foo', ... }, { name: 'bar', ... }]}
<ArrayOfItems>
  <Item>
    ...
  </Item>
  <Item>
    ...
  </Item>
</ArrayOfItems>

How can I force my field to be parsed as an array when converted from xml to object?


Solution

  • I had the same issue with both LoopBack Enterprise SOAP connector and node-soap.

    The easiest workaround I found was to have a simple method which does the following:

    function forceArray(array) {
          if (!array || Array.isArray(array))
            return array;
          else
            return [array];
    }
    

    Does that helps?