JavascriptでArray of ObjectsとObject of Arraysの変換をたまに使うのでメモ。
はじめに
Array of Objects
const array_objects = [
{ age: 40, first_name: 'Dickerson', last_name: 'Macdonald' },
{ age: 21, first_name: 'Larsen', last_name: 'Shaw' },
{ age: 89, first_name: 'Geneva', last_name: 'Wilson' },
{ age: 38, first_name: 'Jami', last_name: 'Carney' }
]
Object of Arrays
const object_arrays = {
age: Array [40, 21, 89, 38],
first_name: Array ["Dickerson", "Larsen", "Geneva", "Jami"],
last_name: Array ["Macdonald", "Shaw", "Wilson", "Carney"]
}
Array of Objects → Object of Array
使いみち
コード
const new_object_arrays = Object.assign(
...Object
.keys(array_objects[0])
.map( key => ({ [key]: array_objects.map( o => o[key] ) }))
);
Object of Array
→ Array of Objects
使いみち
- テーブル系描画系のライブラリに放り込むときのデータ構造
- d3jsのデータ構造
コード
const new_array_object = Object.keys(object_arrays).reduce(
(r, key) =>{
object_arrays[key].forEach(
(value, i) => {
r[i] = r[i] || {}
r[i][key] = value
})
return r
}, [])
または
const new_array_objects = object_arrays[Object.keys(object_arrays)[0]].reduce(
(r, _, i) =>{
r.push(
Object.assign(...Object
.keys(object_arrays)
.map( key => ({ [key]: object_arrays[key][i]})))
)
return r
},[])
No comments:
Post a Comment