Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get all values of a specific key in array of objects?

I have array of objects like this

const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};
const object2 = {
  a: 'somestring2',
  b: 42,
  c: false
};
const object3 = {
  a: 'somestring3',
  b: 42,
  c: false
};
const arr = [object1,object2,object3]

i want to get all the values of ‘a’ key.
so result be

['somestring','somestring2','somestring3']

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried Object.values() but it gets me all values of all keys, which is not the desired output.

>Solution :

Just use map() function:

const arr = [object1,object2,object3].map(({a}) => (a))

An example:

const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};
const object2 = {
  a: 'somestring2',
  b: 42,
  c: false
};
const object3 = {
  a: 'somestring3',
  b: 42,
  c: false
};
const arr = [object1,object2,object3].map(({a}) => (a))
console.log(arr)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading