73
50

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Javascriptのオブジェクトのメンバ数を取るときにlengthプロパティが使えない。

Last updated at Posted at 2016-09-08

jsのある処理で、オブジェクトに2つ以上メンバ数がある際に分岐させるときにつまづいたのでメモ。

普通にこうやったらうまくいかなかった。

var dataList = {
    "apple" : 120,
    "banana": 100
};

if (dataList.length >= 2) {    // dataList.length はundefined
    // ほげほげ
}

調べてみると残念ながらどうやらオブジェクトにlengthプロパティはないらしい。
eachで泥臭くカウントしていくしかないのかと思いきや、この記事のotakaさんのコメントでスマートに解決出来た。

var dataList = {
    "apple" : 120,
    "banana": 100
};

if (Object.keys(dataList).length >= 2) {    // Object.keys(dataList) は["apple","banana"]
    // ほげほげ
}

otakaさん、ありがとうございます!

73
50
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
73
50

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?