最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Lodash check whether an array is array of object? - Stack Overflow

programmeradmin3浏览0评论

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

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
Share Improve this question edited Mar 7, 2017 at 7:43 gyre 16.8k4 gold badges40 silver badges47 bronze badges asked Mar 7, 2017 at 7:33 Alex YongAlex Yong 7,6458 gold badges27 silver badges42 bronze badges 1
  • 1 Well.. actually "array of object" is array too. Furthermore array may contain both objects and scalar values – hindmost Commented Mar 7, 2017 at 7:35
Add a ment  | 

2 Answers 2

Reset to default 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./ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

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);
发布评论

评论列表(0)

  1. 暂无评论