S
S
SvetlanaDubovik2017-06-23 15:29:50
JavaScript
SvetlanaDubovik, 2017-06-23 15:29:50

How to process data if an array of objects or just an object can come?

Hello. Tell me please. I receive data in the form of a JSON file. The structure is something like this:

"Адрес":[
{
    "Регион":{
           "ТипРегион":"область",
            "НаимРегион":"Свердловская"
              }
     }, ...
}, ...
]

How to process such data more correctly, if not only one region object, but also an array can come. I did it in the for(key in obj) loop, but it gives an error if it's not an array, but one object. If you process just for, it also swears. Now I am writing a condition that if the length is unknown, then 1 object and its own handler, if there is a length, then I start the cycle, but, in my opinion, this is terribly clumsy. How to process such a structure more beautifully?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nicholas, 2017-06-23
@SvetlanaDubovik

Do something like:

input = Array.isArray(input) ? input: [input];
// дальше работаем с input как с массивом

E
emp1re, 2017-06-23
@emp1re

Find the one who formed this format of the answer and break a couple of his fingers.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question