get array from objects by key in javascript

You can use the map() method to retrieve an array of specific object key values. Here is an example:

index.tsx
const myObjects = [
  { id: 1, name: "foo" },
  { id: 2, name: "bar" },
  { id: 3, name: "baz" }
];

const myArray = myObjects.map(obj => obj.id);

console.log(myArray); // Output: [1, 2, 3]
191 chars
10 lines

In the example above, we have an array of objects myObjects. We want an array of the id values. We use the map() method to iterate over each object, and return only the id value. The result is stored in myArray variable. Finally, we log the array to the console.

related categories

gistlibby LogSnag