Jeff Adam
Jeff Adam

Reputation: 103

How to check if it is array of objects or array of strings

How to differentiate between an array of objects and an array of strings? How do I determine which array is this?

It could be like this ['foo', 'bar', 'baz'] or

It could be like [ { foo: 'bar' }, { qux: 'quux' } ] And I would like to handle them separately

Upvotes: 0

Views: 825

Answers (4)

CodeVista
CodeVista

Reputation: 51

The quickest way for me to find out what type of contents in the Array is to loop thru the array using the console.dir(). With console.dir see all the properties. You can add the typeof operator to find the type of a JavaScript variable in the console.dir()

const list = ['foo', 'bar', 'baz'];
const list2 = [ { foo: 'bar' }, { qux: 'quux' } ];

list.forEach(item => console.dir(item)); // output: foo, bar, baz
list2.forEach(item => console.dir(item)); //output: Object, Object  

console.dir resource: https://developer.mozilla.org/en-US/docs/Web/API/Console/dir

Upvotes: 0

user10925323
user10925323

Reputation:

You could check if the first item of the array has any object properties.

list1 = [1,2,3,4,5];
var type = typeof(list1[0])

Simple

Upvotes: 2

Elman Huseynov
Elman Huseynov

Reputation: 1147

You can loop this array via foreach or map method and by using operator typeof check type of every item in array.

Upvotes: 0

willwile4
willwile4

Reputation: 63

In JS you can have an array of different data types. Because of this, you'd have to test each item in the array. What do you want to do with this array? That will determine what the code looks like.

Upvotes: 0

Related Questions