11

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.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
summerNight
  • 1,446
  • 3
  • 25
  • 52
  • Is the single item inside an array? If not you can just check if the[variable is an array](http://stackoverflow.com/questions/4775722/check-if-object-is-array). If it is you can check if `array.length == 1`. – Spencer Wieczorek Sep 28 '16 at 14:58
  • Its not a list, its an array... And in js they are a special kind of object, so if you write object methods they also work for an array – Jonas Wilms Sep 28 '16 at 14:59
  • `List` is called _array_ in JavaScript. Also `JSON` is _text data_ - since it stands for "JavaScript Object Notation", then if it's already in JavaScript, it's an object. – VLAZ Sep 28 '16 at 15:06

6 Answers6

41

A one liner using Array.prototype.flat:

[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"}]
stephen.hanson
  • 9,014
  • 2
  • 47
  • 53
oli
  • 1,909
  • 17
  • 14
18

You can simply use Array.concat() to auto-wrap an object into an array:

const obj = {name: "foo"};
const arr = [{name: "bar"}];

const result1 = [].concat(obj); // result1 is [{name: "foo"}]
const result2 = [].concat(arr); // result2 is [{name: "bar"}]

console.log(result1)
console.log(result2)
SimoAmi
  • 1,696
  • 14
  • 13
  • 2
    This is a safer option than using .flat() as it works for both objects and single values. eg: Both `const item1 = "string";` and `const item2 = {value: "string"};` Will safely return `const result = [].concat(item1); // still works and returns ["string"]` and `const result = [].contact(item2); // still works and returns [{value:"string" }]` – ToddPadwick May 25 '21 at 08:02
8

you can transform it in an array if is not and let iterate one time:

function loadJSONIntoUI(data) {

    if(!(data instanceof Array)){
       data = [data];
    }

    for (var aMsg = 0; aMsg < data.length; aMsg++) {
        // Do something with each `index` in the List
    }
}

Also, length doesn't need to be called like a method.

Let me know if it works

Cheers

Roberto Lonardi
  • 569
  • 2
  • 10
5

Array.isArray can be used to achieve what you need:

function loadJSONIntoUI(data) {
    if(!Array.isArray(data)) {
        data = [data];
    }
    for (var aMsg = 0; aMsg < data.length(); aMsg++) {
        // Do something with each `index` in the List
    }
}
tcooc
  • 20,629
  • 3
  • 39
  • 57
  • FYI: This only works in IE9+ https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray – R. Chappell Sep 28 '16 at 15:02
3

You need to check for an array and fix an error - should be just data.length, no brackets. See code below, check demo - https://fiddle.jshell.net/ermakovnikolay/fgedaubm/

function loadJSONIntoUI(data) {
    var data = Array.isArray(data) ? data : [ data ];
    for (var aMsg = 0; aMsg < data.length; aMsg++) {
        // Do something with each `index` in the List
        console.log(data[aMsg]);
    }
}
Nikolay Ermakov
  • 5,031
  • 2
  • 11
  • 18
  • Again: FYI: This only works in IE9+ https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray – R. Chappell Sep 28 '16 at 15:03
-1

You can use Array.of(). So in your case Array.of(data) returns [{ "name" : "I am not in a List"}]

Sukh N
  • 7
  • 1