MemoryLeak MemoryLeak - 18 days ago 5
Javascript Question

How to get the value from an array which has key/value pair objects?

In the below array, I have objects with key/value pairs

var options = [{
key: "select",
value: null
}, {
key: "one",
value: "First Option"
},
{
key: "second",
value: "Second Option"
}];


how to get the value based on key from options array?

For example, if the key is "select" it should return null,
if the key is "one" it should return "First Option".

Answer

ES6 has the find-function for arrays:

var val = options.find(function(o){ return o.key==="select" }).value;

And maybe wrap it in a function of your own to make it a bit more reusable:

function findValue(arr, key){
  return arr.find(function(o){ return o.key===key }).value;
}

var val = findValue(options,"select");

I would argue this is the most semantically correct answer without modifying the original array, but you must have realized by now that there are many ways to skin this cat. (I like Zodiac Zubeda's answer because it's a simple for-loop so fast and backwards compatible and has the break that skips unnecessary iterations.)

Comments