3
1

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] Mapと連想配列の相互変換 - 深い階層も変換

Last updated at Posted at 2018-01-18

[JavaScript] Mapと連想配列の相互変換
の続きです。

せっかく作ったので、連想配列の値が連想配列だったりとか、Mapの要素がMapだった場合にも変換できるように修正してみました。

使い方

let object = {id: 1, name: 'mk'}

let map = objectToMap(object) // -> Map {'id' => 1, 'name' => 'mk'}

mapToObject(map) // -> {id: 1, name: 'mk'}

2つめの引数に{deep:true}を渡すと、ディープな変換をします。

let object = {id: 1, name: 'mk', profile: {
  blood: 'O', like: 'カレー', address: {
    pref: 'Tokyo', city: 'Yoyogi'}}}

let map = objectToMap(object, {deep: true})
// -> Map {'id' => 1, 'name' => 'mk', 'profile' => Map {
//      'blood' => 'O', 'like' => 'カレー', 'address' => Map {
//        'pref' => 'Tokyo', 'city' => 'Yoyogi' } } }

mapToObject(map, {deep: true})
// -> {id: 1, name: 'mk', profile: {
//      blood: 'O', like: 'カレー', address: {
//        pref: 'Tokyo', city: 'Yoyogi'} } }

ソースコード

map_object_convert.js
'use strict'

const mapToObject = (map, {deep = false} = {}) =>
  [...map].reduce((l, [k, v]) =>
    Object.assign(l, {[k]: deep && isMap(v) ? mapToObject(v, {deep}) : v}), {})

const objectToMap = (object, {deep = false} = {}) =>
  new Map(Object.entries(object).map(([k, v]) =>
    [k, deep && isObject(v) ? objectToMap(v, {deep}) : v]))

const is = constructor =>
  something =>
    something !== undefined &&
    something !== null &&
    something.constructor === constructor

const isObject = is(Object)

const isMap = is(Map)

export {mapToObject, objectToMap}

3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?