0
0

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 3 years have passed since last update.

【JavaScript】オブジェクトを配列に変換( {a: 1, b: 2}を[[a, 1], [b, 2]]に )

Posted at

実現したいこと

下記のようなオブジェクトを、

const OBJECT = {
    2021-09-01: 1, 
    2021-09-02: 1, 
    2021-09-03: 1, 
    2021-09-04: 1, 
    2021-09-05: 1, 
    2021-09-06: 1, 
    2021-09-07: 1
}

下記の配列に変換したい。

[
    ['2021-09-01', 1],
    ['2021-09-02', 1],
    ['2021-09-03', 1],
    ['2021-09-04', 1],
    ['2021-09-05', 1],
    ['2021-09-06', 1],
    ['2021-09-07', 1]
]

対応方法

Object.entries()メソッドを使う。

Object.entries()メソッドは、引数に与えたオブジェクトが持つ、文字列をキーとしたプロパティの組 [key, value] からなる配列を返す。

const RESULT = Object.entries(OBJECT);

プロパティ名だけ取り出して、配列にする方法

Object.keys()メソッドを使う。

Object.keys()メソッドは、引数に与えたオブジェクトが持つプロパティの名前の配列を、通常のループで取得するのと同じ順序で返す。

const RESULT = Object.keys(OBJECT);

下記の配列が得られる。

[
    '2021-09-01', 
    '2021-09-02', 
    '2021-09-03', 
    '2021-09-04', 
    '2021-09-05', 
    '2021-09-06', 
    '2021-09-07'
]

参考

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?