Skip to content

Instantly share code, notes, and snippets.

@barneycarroll
Created February 15, 2021 23:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barneycarroll/3035d12778433c2a49ac0e9dd5922b80 to your computer and use it in GitHub Desktop.
Save barneycarroll/3035d12778433c2a49ac0e9dd5922b80 to your computer and use it in GitHub Desktop.
Produce keyed objects from a matrix (2-dimensional array) or vice-versa
export default function matrix(keys){
return subject => (
Array.isArray(subject)
?
Object.fromEntries(
keys.flatMap((key, index) =>
key == null ? [] : [[key, subject[index]]]
)
)
:
keys.map(key => subject[key])
)
}

Supply an array of keys and map over an array of structured data. If the array is a matrix (2-dimensional array), it will produce an array of objects with the keys taking the values at the respective index; if it consists of objects, the selected keys produce an array of those values:

const fields = [
  ['Your Name',     'username', 'text'    ],
  ['Email address', 'email',    'text'    ],
  ['Password',      'Password', 'Password'],
]

const inputs = fields.map(matrix(['label', 'name', 'type']))

// 👇 Arrays are transformed into objects with keys assigned by index
//
// {label: 'Your Name',     name: 'username', type: 'text'    },
// {label: 'Email address', name: 'email',    type: 'text'    },
// {label: 'Password',      name: 'Password', type: 'Password'},

inputs.map(matrix(['name', 'label', 'type']))

// 👇 Objects are transformed into arrays with keyed properties in the given ordered
//
// ['username', 'Your Name',     'text'    ],
// ['email',    'Email address', 'text'    ],
// ['Password', 'Password',      'Password'],

inputs.map(matrix(['name', 'type']))

// 👇 Keys can be omitted to extract only pertinent data
//
// ['username', 'text'    ],
// ['email',    'text'    ],
// ['Password', 'Password'],

fields.map(matrix([,'name', 'type'))

// 👇 The same can be achieved for matrices by leaving empty slots at the relevant indices in the keys array
//
// {name: 'username', type: 'text'    },
// {name: 'email',    type: 'text'    },
// {name: 'Password', type: 'Password'},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment