0

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

3
  • 4
    Something like typeof arrayOfSuspiciousEntities[0] comes to mind. Commented Apr 10, 2019 at 20:09
  • 1
    Please use few more words to explain question better. probably an example would do Commented Apr 10, 2019 at 20:13
  • Just added an example Commented Apr 10, 2019 at 20:24

4 Answers 4

2

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

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

Comments

0

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.

2 Comments

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
Noah Gerrad's answer is a good starting point, test the first item in the array using typeof myArray[0]
0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.