5

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']

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

1

2 Answers 2

4

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)

Sign up to request clarification or add additional context in comments.

2 Comments

it returns [{a: 'somestring'},{a: 'somestring2'}, {a: 'somestring3'}] i want it to return ['somestring','somestring2','somestring3']
@Abdel-Rahman please, see my updated answer
1

Have you tried const arr = [object1.a, object2.a, object3.a]? That might work

2 Comments

Nothing in JavaScript is encapsulated by default. There are ways to do it, but without those explicit techniques, all properties and methods are available. Also, while your answer would produce the correct result, I believe they wanted a general solution that doesn't require explicitly knowing about all the elements of the array.
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.