Loop through object get value using regex key matches Javascript

后端 未结 5 1410
一整个雨季
一整个雨季 2021-01-04 11:15
var obj = {
 Fname1: \"John\",
 Lname1: \"Smith\",
 Age1: \"23\",
 Fname2: \"Jerry\",
 Lname2: \"Smith\",
 Age2: \"24\"
}

with an object like this.

5条回答
  •  孤城傲影
    2021-01-04 12:01

    Quick key matcher using includes()

    I love the new includes function. You can use it to check for the existence of a key or return its value.

    var obj = {
       Fname1: "John",
       Lname1: "Smith",
       Age1: "23",
       Fname2: "Jerry",
       Lname2: "Smith",
       Age2: "24"
    };
    var keyMatch = function (object, str) {
    for (var key in object) {
        if (key.includes(str)) {
            return key;
        }
    }
    return false;
    };
    var valMatch = function (object, str) {
    for (var key in object) {
        if (key.includes(str)) {
            return object[key];
        }
    }
    return false;
    };
    
    // usage
    
    console.log(keyMatch(obj, 'Fn')) // test exists returns key => "Fname1"
    console.log(valMatch(obj, 'Fn')) // return value => "John"
        

    If you haven't got ES2015 compilation going on, you can use

    ~key.indexOf(str)

提交回复
热议问题