I have a function that takes in an Array
, iterates over it finding all Objects
and displays them to the UI.
In rare cases, I have to supply an Object
(result from a WS
as application/JSON
) which is not an Array
by default and hence my function fails to iterate over it and display on the UI.
In normal cases my Array
looks like this:
[
{ "name" : "foo"},
{ "name" : "bar"},
{ "name" : "baz"}
]
and this works like it is supposed to. However, sometimes the data I get could be this:
{ "name" : "I am not in a List"}
and my function that takes in an array looks like this:
function loadJSONIntoUI(data) {
for (var aMsg = 0; aMsg < data.length(); aMsg++) {
// Do something with each `index` in the List
}
}
Is there a way I can detect that the single object which is not an array is an odd one and probably put it into a List on the fly and pass it to a function?
So far I have tried to use typeof
and also tried to create a new Array
on the fly and push
my object into it but it prints out a 1
when I do that.
A one liner:
[couldBeArray].flat()
Examples:
const anObj = {name: "Hi"};
const anArr = [{name: "Hi"}];
const wrapped1 = [anObj].flat()
const wrapped2 = [anArr].flat()
console.log(wrapped1); // wrapped1 is [{name: "Hi"}]
console.log(wrapped2); // wrapped2 is [{name: "Hi"}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With