John M
John M

Reputation: 197

javascript lookup value of a map object which is array of array

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

Upvotes: 1

Views: 3286

Answers (2)

LukStorms
LukStorms

Reputation: 29677

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()])

Upvotes: 1

Yousername
Yousername

Reputation: 1012

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);

Upvotes: 1

Related Questions