Maps an object to an array of objects using the provided mapping function.
- Use Object.entries() to get an array of key-value pairs for an object.
- Use Array.prototype.reduce() to map arrays to objects.
- Used to map the keys and values of an object, and
mapFn
Array.prototype.push() to add the mapped value to the array.
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 } ]