Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS getting value of object with key starting with a string

Is there a quick way to get the value of a key starting with a certain string?

Example :

var obj = {
  "key123" : 1,
  "anotherkey" : 2
}

obj['key1'] // would return 1
obj['ano'] // would return 2

Thanks

like image 976
Samuel Rondeau-Millaire Avatar asked Feb 08 '16 21:02

Samuel Rondeau-Millaire


2 Answers

You can create a helper function

function findValueByPrefix(object, prefix) {
  for (var property in object) {
    if (object.hasOwnProperty(property) && 
       property.toString().startsWith(prefix)) {
       return object[property];
    }
  }
}

findValueByPrefix(obj, "key1");

As Kenney commented, the above function will return first match.

like image 187
Aseem Gautam Avatar answered Oct 19 '22 02:10

Aseem Gautam


You could use find on the entries of the object. IF there's a key which starts with, access the index at 1 to get the value.

Object.entries(o).find(([k,v]) => k.startsWith(part))?.[1]

Here's a snippet:

const getValue = (part, o) => Object.entries(o).find(([k, v]) => k.startsWith(part))?.[1]

const obj = {
  "key123": 1,
  "anotherkey": 2
}

console.log(
  getValue('key', obj),
  getValue('ano', obj),
  getValue('something', obj),
)
like image 3
adiga Avatar answered Oct 19 '22 03:10

adiga