4

I couldn't find any Lodash method that can differentiate between a normal (e.g. integer) array and array of objects, since JavaScript treats object as array.

like both will return true

console.log(_.isArray([1,2,3])); // true
console.log(_.isArray([{"name":1}])); // true
1
  • 1
    Well.. actually "array of object" is array too. Furthermore array may contain both objects and scalar values Commented Mar 7, 2017 at 7:35

2 Answers 2

12

You can use _.every, _.some, and _.isObject to differentiate between arrays of primitives, arrays of objects, and arrays containing both primitives and objects.

Basic Syntax

// Is every array element an object?
_.every(array, _.isObject)
// Is any array element an object?
_.some(array, _.isObject)
// Is the element at index `i` an object?
_.isObject(array[i])

More Examples

var primitives = [1, 2, 3]
var objects = [{name: 1}, {name: 2}]
var mixed = [{name: 1}, 3]

// Is every array element an object?
console.log( _.every(primitives, _.isObject) ) //=> false
console.log( _.every(objects,    _.isObject) ) //=> true
console.log( _.every(mixed,      _.isObject) ) //=> false

// Is any array element an object?
console.log( _.some(primitives, _.isObject) ) //=> false
console.log( _.some(objects,    _.isObject) ) //=> true
console.log( _.some(mixed,      _.isObject) ) //=> true
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

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

9 Comments

I just want to check whether a property has object or not, I need not to check everything, imagine I have one object has 100 nested object and array object, __.some is overkills.
Ok, so you just want to check at a single index? That isn't too hard. I can add that to the basic syntax above.
Nope, it doesn't. See the edited Basic Syntax section above.
hey i found some problem. jsbin.com/vuluzejetu/1/edit?html,js,console isObject doesn't work as expected. lol.
Could you paste the code here? It's not showing for me on JSBin, all I see is isArray and a space afterwards in the JS section.
|
1

This should do the job

_.every(yourArray, function (item) { return _.isObject(item); });

This will return true if all elements of yourArray are objects.

If you need to perform partial match (if at least one object exists) you can try _.some

_.some(yourArray, _.isObject);

1 Comment

both _.every and _.some loop through ur entire set of property, how to check on specified property's value?

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.