Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to safely wrap an object into an array in JavaScript

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.

like image 544
summerNight Avatar asked Nov 26 '22 21:11

summerNight


1 Answers

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"}]
like image 148
oli Avatar answered Dec 15 '22 00:12

oli