0

Given these two arrys:

[ {
  "0" : "e34712",
  "1" : "1768-01-19",
  "2" : "Robert Thomas",
  "3" : "Richard Morris"
}, [etc]]

and

[ {
  "0" : "e34712",
  "1" : "1768-01-19",
  "2" : "Robert Thomas",
  "3" : [ "William Morris; ", "Richard Morris" ]
}, [etc]]

how can I get the number of items in the third element, as in '1' for the first array and '2' in the second one? If I do record[3].length I get '2', as expected, for the second one, although I get the length of the string for the first one, i.e. if there's only one item in the third position.

I need to do this:

result.forEach(function (record) {
                  record[3] = record[3].join('')
                })

which doesn't work if record[3] has only one item, so I'd like to add an 'if record[3] contains more than one item then do the .join, otherwise pass'. If I do

if record[3].length > 2 it also catches single strings which contains only three or four characters, which of course I don't want.

HBMCS
  • 686
  • 5
  • 25
  • 1
    Is that really the structure you have? because it differs from your [last question](https://stackoverflow.com/q/60873549/215552), which was an array of arrays, not an array of objects. – Heretic Monkey Mar 26 '20 at 21:02
  • Yes, it differs because I edited the way XQuery outputs my JSON so that I can achieve what I want here. – HBMCS Mar 26 '20 at 21:29

1 Answers1

2

You can check if the third item is an array. If it is, you do the join. If not, you skip it.

result.forEach(function (record) {
  if (Array.isArray(record[3])) {
    record[3] = record[3].join('');
  }
});