Skip to content

Instantly share code, notes, and snippets.

@HichamBenjelloun
Last active April 5, 2021 13:51
Show Gist options
  • Save HichamBenjelloun/94a2211bc20a1209d542273da631d576 to your computer and use it in GitHub Desktop.
Save HichamBenjelloun/94a2211bc20a1209d542273da631d576 to your computer and use it in GitHub Desktop.
Rearrange object structure
import _ from 'lodash';
const isPlainObject = value =>
value === Object(value) &&
!Array.isArray(value);
function* leaves(node, path = []) {
if (!isPlainObject(node)) {
return yield {value: node, path};
}
for (const [key, childNode] of Object.entries(node)) {
yield* leaves(childNode, [...path, key]);
}
}
const applyPermutation = (arr, perm) => arr.map((_, idx) => arr[perm[idx]]);
function rearrange(node, permutation) {
const output = {};
for (const {path, value} of leaves(node)) {
_.set(output, applyPermutation(path, permutation), value);
}
return output;
}
export {rearrange};
@HichamBenjelloun
Copy link
Author

Usage:

const grades = {bob: {math: 10, french: 20,}, alice: {math: 14, french: 15,}}
rearrange(grades, [1, 0]); // => { math: { bob: 10, alice: 14 }, french: { bob: 20, alice: 15 } }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment