0
const pairs = { a : 1, b : 2, c : 3 }
const keyArray = [a, b, c]

I'm trying to get a function or w/e that returns [1, 2, 3]. can't think of anything please help

4
  • Is it JavaScript? Commented Mar 11, 2022 at 22:37
  • yeah this is javascript Commented Mar 11, 2022 at 22:39
  • 1
    what have you tried so far? Commented Mar 11, 2022 at 22:45
  • Are you trying to find the values in pairs that have keys specified in keyArray? Commented Mar 11, 2022 at 22:51

4 Answers 4

1

In javascript all keys of an object are actually strings, and can be addressed using the same strings.

Your code is creating an array containing the values of the - possibly uninitialized - variables a, b and c, which then produces [undefined, undefined, undefined], or else whatever those variables contain.

You need to make keyArray contain strings instead, and then you can use the map() function to produce the desired result:

const pairs = { "a" : 1, "b" : 2, "c": 3 }
const keyArray = ["a", "b", "c"]
const values = keyArray.map(key => pairs[key]);
console.log(values);

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

1 Comment

For my money, this is the better/best answer.
0
const pairs = { 'a' : 1, 'b' : 2, 'c': 3 }
const keyArray = ['a', 'b', 'c']

for(const item of keyArray)
{
    console.log(pairs[item])
}

You need to make your items inside the array and object as strings

2 Comments

thanks for the help. it actually worked i was stuck on it for a while
I am glad that I could help you. Happy Coding 😀
0

Well since it's Javascript

Object.values() should do it.

const keyArray = Object.values(pairs)

Comments

0
const pairs = { 'a' : 1, 'b' : 2, 'c': 3 }

for(const [key , value] of Object.entries(pairs))
{
    console.log(key) // a , b, c
    console.log(value) // 1, 2, 3
}

Comments

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.