Lodash检查数组是否是对象数组?

时间:2017-03-07 07:33:13

标签: javascript underscore.js lodash

我无法找到任何可以区分普通(例如整数)数组和对象数组的Lodash方法,因为JavaScript将对象视为数组。

两者都会返回true

console.log(_.isArray([1,2,3])); // true
console.log(_.isArray([{"name":1}])); // true

2 个答案:

答案 0 :(得分:6)

您可以使用_.every_.some_.isObject来区分基元数组,对象数组以及包含基元和对象的数组。

基本语法

// 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])

更多例子



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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

这应该做的工作

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

如果true所有元素都是对象,则会返回yourArray

如果您需要执行部分匹配(,如果至少存在一个对象),您可以尝试_.some

_.some(yourArray, _.isObject);