snippetjavascriptTip
Map a JavaScript object to an array
Viewed 0 times
mapjavascriptobjectarray
Problem
Ever wanted to map an object to an array of objects using a custom mapping function? This can be useful when you need to separate a dictionary-like object into individual objects, including the keys as properties.
The simplest way to get the key-value pairs of an object is to use
Conversely, what about the opposite? You can simply use
The simplest way to get the key-value pairs of an object is to use
Object.entries(). Then, using Array.prototype.map() and a mapping function, you can map the key-value pairs to an array of objects.Conversely, what about the opposite? You can simply use
Object.fromEntries() to convert an array of objects to an object. The mapFn function should return a 2-element array with the key-value pair.Solution
const listify = (obj, mapFn) =>
Object.entries(obj).map(([key, value]) => mapFn(key, value));
const people = [
{ name: 'John', age: 42 },
{ name: 'Adam', age: 39 },
];
listify(people, (key, value) => ({ name: key, ...value }));
// [ { name: 'John', age: 42 }, { name: 'Adam', age: 39 } ]Conversely, what about the opposite? You can simply use
Object.fromEntries() to convert an array of objects to an object. The mapFn function should return a 2-element array with the key-value pair.Code Snippets
const listify = (obj, mapFn) =>
Object.entries(obj).map(([key, value]) => mapFn(key, value));
const people = [
{ name: 'John', age: 42 },
{ name: 'Adam', age: 39 },
];
listify(people, (key, value) => ({ name: key, ...value }));
// [ { name: 'John', age: 42 }, { name: 'Adam', age: 39 } ]const delistify = (arr, mapFn) => Object.fromEntries(arr.map(mapFn));
const people = [
{ name: 'John', age: 42 },
{ name: 'Adam', age: 39 },
];
delistify(people, (obj) => {
const { name, ...rest } = obj;
return [name, rest];
});
// { John: { age: 42 }, Adam: { age: 39 } }Context
From 30-seconds-of-code: listify
Revisions (0)
No revisions yet.