map object in javascript

To map an object in JavaScript, you can use the Object.keys() method to get an array of the object's keys. Then, you can use the Array.prototype.map() method to iterate over the keys and perform operations on each key-value pair.

Here's an example:

index.tsx
const obj = {
  name: 'John',
  age: 30,
  city: 'New York'
};

const mappedObj = Object.keys(obj).map(key => ({
  [key]: obj[key]
}));

console.log(mappedObj);
161 chars
12 lines

In the above example, Object.keys(obj) returns an array of keys: ['name', 'age', 'city']. Then, the map() method is called on this array and a new object is created for each key. Finally, the mapped object is logged to the console:

index.tsx
[ { name: 'John' }, { age: 30 }, { city: 'New York' } ]
56 chars
2 lines

Note that the mapped object is an array of individual objects, where each object contains a single key-value pair from the original object.

related categories

gistlibby LogSnag