1

I want to run map() on a variable that might either be a single object or an array. However, I can't do this if the variable is an object as that throws an error.

I tried using the spread operator to make sure the variable turns into an array but apparently that doesn't work either:

// items can either be an object or an array of objects
renderedItems = [...items]
    .filter(item => !!item)
    .map((item, index) => _this.renderItem(item, index));

How can I make sure the variable I'm doing a filter() and map() on is an array? I heard Array.isArray isn't fully supported yet.

2
  • Is the object array-like? Commented Jul 24, 2018 at 0:20
  • Array.isArray is widely supported now : caniuse.com/#search=isArray Commented Jul 24, 2018 at 0:25

1 Answer 1

2

You can use instanceof to check if the variable is an Array.

if(variable instanceof Array){
  //variable is an Array
} else {
  //variable is not an Array
}

var array = [1, 2, 3, 4, 5];
var str = "String";
function isArray(obj){
 return obj instanceof Array;
}
console.log("array is an Array: "+isArray(array));
console.log("str is an Array: " + isArray(str));

You can also use Array.isArray.

if(Array.isArray(variable)){
 //variable is an Array
} else {
  //variable is not an Array
}

var array = [1, 2, 3, 4, 5];
var str = "String";
function isArray(obj){
    return Array.isArray(obj);
}
console.log("array is an Array: "+isArray(array));
console.log("str is an Array: " + isArray(str));

You can check if the variable's constructor is equal to Array.

 var array = [1, 2, 3, 4, 5];
var str = "String";
function isArray(obj){
        return obj.constructor === Array;
 }
 console.log("array is an Array: "+isArray(array));
console.log("str is an Array: " + isArray(str));

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.