Samuel Rondeau-Millaire February 2016

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

Answers


Aseem Gautam February 2016

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.


Michael Warner February 2016

There is no truly easy way to do this as javascript objects are hash tables and you need the key in it's entire form to pull the memory address of the value it holds.

I would make it a function and append it to the prototype of the object so we have access to this function in all hash tables (javascript objects)

Object.prototype.getBy = function(value){
    for(var key in obj){
        if(key.search(value) != -1){
            return obj[key];
        }
    }
}

//so this should work
var obj = {
    "key123" : 1,
    "anotherkey" : 2
}
obj.getBy('ano'); //returns 2

//This should as well
var differentObj = {
    "somekey" : 1,
    "anotherkey" : 2
}
differentObj.getBy('some'); //returns 1


RomanPerekhrest February 2016

Search for the first match of the property name which begins with specified string:

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

    function getObjectValueByPartialName(obj, name){
        if (typeof obj !== "object") {
            throw new Error("object is required!");
        }
        for (var prop in obj) {
            if (prop.indexOf(name) === 0){
                return obj[prop];
            }
        }
        return "no such property!";
    }

    console.log(getObjectValueByPartialName(obj, 'some'));  // output: 3
    console.log(getObjectValueByPartialName(obj, 'key1'));  // output: 1

Post Status

Asked in February 2016
Viewed 3,289 times
Voted 5
Answered 3 times

Search




Leave an answer