Map an object to an array

JavaScript, Object, Array · Feb 5, 2023

Maps an object to an object array, using the provided mapping function.

const listify = (obj, mapFn) =>
  Object.entries(obj).reduce((acc, [key, value]) => {
    acc.push(mapFn(key, value));
    return acc;
  }, []);
const people = { John: { age: 42 }, Adam: { age: 39 } };
listify(people, (key, value) => ({ name: key, ...value }));
// [ { name: 'John', age: 42 }, { name: 'Adam', age: 39 } ]

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this

  • Map an array to an object

    Maps an object array to an object, using the provided mapping functions.

    JavaScript, Array · Feb 4, 2023

  • Map object keys

    Maps the keys of an object using the provided function, generating a new object.

    JavaScript, Object · Oct 21, 2020

  • Map object values

    Maps the values of an object using the provided function, generating a new object with the same keys.

    JavaScript, Object · Oct 21, 2020