1

I have a JS map object (new to JS here) which is an array of array like so:

scores=[["key_1",true],["key_2",false],["key_3",false]....["key_n",true]]

I am able to access the values on the console like so:

scores[0] //outputs ["key_1",true]
scores[0][0] //outputs "key_"
//..and so on.

How do I however make a (fast) lookup for a particular key in the object array, something like:

scores[["key_3"]] //obviously wont work
//expected output: false
4
  • 3
    lookup = new Map(scores); lookup.get('key_3') Commented Dec 27, 2019 at 22:18
  • You also might want to consider using a Set() or an object with attributes if you're simply dealing with key/value pairs. Commented Dec 27, 2019 at 22:23
  • @JonTrent A Map, as in Patrick's comment, works with arrays of arrays and is as efficient as an object or Set. Commented Dec 27, 2019 at 22:27
  • @PatrickRoberts: please post this as an answer and I will accept this. This looks elegant. Commented Dec 27, 2019 at 22:28

2 Answers 2

1

Use Object.fromEntries() to turn the array into an object.

Use Object.entries() to change back into array.

var scores = [
  ["key_1", true],
  ["key_2", false],
  ["key_3", false],
  ["key_4", true]
];

scores = Object.fromEntries(scores);

console.log(scores.key_3);

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

Comments

1

You can simply find the key.

const scores=[ ["key_1",true], ["key_2",false], ["key_3",false], ["key_4",true] ];

var score = scores.find(score => score[0]==="key_3")

console.log(score[0]+" is "+score[1])

Returns:

key_3 is false

You could also transform the array-of-arrays to a Map object.

To get an easy access to the key-value pairs, while it's still iterable.

const scores=[ ["key_1",true], ["key_2",false],["key_3",false], ["key_4",true] ]

var scoreMap = new Map();
scores.forEach(score => scoreMap.set(score[0], score[1]))
 
console.log("key_4 is "+ scoreMap.get("key_4"))
 
console.log([...scoreMap.keys()])

3 Comments

@LukStroms: For some reason, I like Patrick's answer.. Thoughts?
@JohnM If you do console.log(scores) after it, then you'll notice that his method turned the 2D array into an object. So if you use that trick, then I would probably use another variable name for it.
@JohnM I realised that since that array is basically containing key-value pairs, that using find for each key is indeed not optimal. So an alternative was added.

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.