Skip to content

Instantly share code, notes, and snippets.

@thesofakillers
Last active February 26, 2024 16:15
Show Gist options
  • Save thesofakillers/bcf39eaed428304ddc126ca8f12336f7 to your computer and use it in GitHub Desktop.
Save thesofakillers/bcf39eaed428304ddc126ca8f12336f7 to your computer and use it in GitHub Desktop.
JS: Convert Object of Arrays to Array of Objects
/**
* Converts an Object of Arrays to an Array of Objects
* @param {Object} object_arrays An object of arrays where each array is of the same length
* @returns {Array<Object>} An Array of objects where each key in each object corresponds to that element in the original array
*/
function obj_arraysTOarray_objs(object_arrays){
let final_array = object_arrays[Object.keys(object_arrays)[0]].map(
// el is unused, but needs to be defined for map to give access to index i
(_el, i) => {
let internal_object = {};
Object.keys(object_arrays).forEach(
key => (internal_object[key] = object_arrays[key][i])
);
return internal_object;
}
);
return final_array;
}
// ----- Example -------
// You have an object of arrays
let original_object = {
foo: ["el1", "el2", "el3"],
bar: ["diff_el1", "diff_el2", "diff_el3"]
}
// But would like to get an equivalent array of objects
let new_format = obj_arraysTOarray_objs(original_object)
// like this
console.log(new_format)
// what is printed to console
// [
// {
// foo: "el1",
// bar: "diff_el1"
// },
// {
// foo: "el2",
// bar: "diff_el2"
// },
// {
// foo: "el3",
// bar: "diff_el3"
// }
// ]
// As long as the arrays in `original_object` are of the same length, and you're happy keeping the key names.
// Can easily be extended.
@LuisTalavera
Copy link

Great!!! Grazie mille

@omeiirr
Copy link

omeiirr commented Nov 12, 2021

Just what I needed. Thank you! 💯

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