var obj = {
Fname1: \"John\",
Lname1: \"Smith\",
Age1: \"23\",
Fname2: \"Jerry\",
Lname2: \"Smith\",
Age2: \"24\"
}
with an object like this.
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)