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】配列内部のオブジェクトのプロパティ名を変更(map関数)

Last updated at Posted at 2021-09-23

実現したいこと

JavaScriptにjson形式で渡した配列に対して、オブジェクトのプロパティ名を変更して、特定のプロパティのみ取り出した配列を新たに作りたかった。

具体的には、JavaScriptで、下記のように元の配列から新しい配列を作りたい。

元の配列

[
    {status: 1, name: '新規受付', orders_count: 10},
    {status: 2, name: '入金待ち', orders_count: 5},
    {status: 3, name: 'キャンセル', orders_count: 5},
    {status: 4, name: '取り寄せ中', orders_count: 4},
    {status: 5, name: '発送済み', orders_count: 4},
    {status: 6, name: '入金済み', orders_count: 3},
    {status: 7, name: '決済処理中', orders_count: 2}
]

欲しい配列

[
    {name: '新規受付', y: 10},
    {name: '入金待ち', y: 5},
    {name: 'キャンセル', y: 5},
    {name: '取り寄せ中', y: 4},
    {name: '発送済み', y: 4},
    {name: '入金済み', y: 3},
    {name: '決済処理中', y: 2}
]

対応方法

元の配列、ORDERS_COUNT_STATUSES

ORDERS_COUNT_STATUSES = [
    {status: 1, name: '新規受付', orders_count: 10},
    {status: 2, name: '入金待ち', orders_count: 5},
    {status: 3, name: 'キャンセル', orders_count: 5},
    {status: 4, name: '取り寄せ中', orders_count: 4},
    {status: 5, name: '発送済み', orders_count: 4},
    {status: 6, name: '入金済み', orders_count: 3},
    {status: 7, name: '決済処理中', orders_count: 2}
]

map()関数を使って、必要なプロパティのみ取り出し、プロパティ名を変更して配列を作る。

// map()関数を使う
const RESULT = ORDERS_COUNT_STATUSES.map((item) => ({
    name: item['name'], 
    y: item['orders_count']
}));

map()関数について

map()は元となる配列から新しい配列を作成する関数。

let array = [ 配列データ ]
array.map( コールバック関数, オブジェクト );

コールバック関数には3つの引数を与えることができる。

  • currentValue:現在処理中の要素の値
  • index:現在処理中の要素の配列内における添字(省略可)
  • array:mapが実行されている配列(省略可)

第二引数

  • thisArg:コールバック関数内のthisを指すオブジェクトをバインドする(省略可)
array.map(function callback( currentValue[, index[, array]]) {
    // 新しい配列の要素を返す
}[, thisArg])

コールバック関数はアロー関数を使って書いたほうがシンプルに記述できるので、今回はアロー関数で記述。

他の使用例

特定のプロパティのみを取り出した配列を作る場合、

const RESULT = ORDERS_COUNT_STATUSES.map(item => item.orders_count);

下記のような配列が作れる。

[10, 5, 5, 4, 4, 3, 2]

reduce()で合計値を求めることもできる

const SUM = RESULT.reduce( (a, b) => a + b );

参考

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?