lodash:检查对象是空的

时间:2016-05-30 10:59:12

标签: javascript lodash

我有这个对象: {"": undefined}

当我以这种方式检查此对象为空时: _.isEmpty({"": undefined})

我得到false结果,也许在lodash我们有另一种方法?

5 个答案:

答案 0 :(得分:19)

_.isEmpty(obj, true)



var obj = {
  'firstName': undefined
, 'lastName' : undefined
};

console.log(_.isEmpty(obj)); // false

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
&#13;
&#13;
&#13;

请参阅pytransitions

答案 1 :(得分:12)

您的示例对象 为空所以您可能想要测试所有属性是否未定义

let o = {foo: undefined};
!_.values(o).some(x => x !== undefined); // true

答案 2 :(得分:1)

这取决于您要如何检查它。 要检查someevery

吗?

然后你可以做的是:

Sub VAT()

Dim wb As Workbook
Dim ws1, ws2 As Worksheet
Set wb = ActiveWorkbook
Set ws1 = wb.Sheets("Table A")
Set ws2 = wb.Sheets("Table B")


Dim LastRowA, LastRowB As Long
LastRowA = ws1.Range("A" & Rows.Count).End(xlUp).Row
LastRowB = ws2.Range("A" & Rows.Count).End(xlUp).Row


Dim A, r, ra As Range
Dim k As Integer
k = 1
Set A = ws2.Range("A2:A" & LastRowB)

For Each r In A

    Set ra = ws1.Cells.Find(What:=r.Value, LookIn:=xlValues, LookAt _
        :=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
        False, SearchFormat:=False)

    If ra Is Nothing Then

        ws2.Rows(r.Row).Copy Destination:=ws1.Rows(LastRowA + k)
        k = k + 1
        Else
        ws2.Rows(r.Row).Copy Destination:=ws1.Rows(ra.Row)

    End If
Next r

End Sub

答案 3 :(得分:0)

在您的情况下,不能将其称为空对象(Object.values(obj).length将返回1),但是对于完全空的对象,可以使用它:

import { matches } from 'lodash';
matches(obj, {});

答案 4 :(得分:0)

我想这有点矫枉过正,但这也是我使用的递归检查嵌套对象并使用 lodash 的方法。

function checkEmptyObject(obj) {
  if (_.isEmpty(obj)) return true;
  return _.isEmpty(
    Object.entries(obj)
      .map(([key, value]) => {
        if (_.isEmpty(value)) return true;
        if (value instanceof Object) return checkEmptyObject(value);
        return false;
      })
      .filter((b) => b === false)
  );
}