Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save adamrosloniec/7cbd29554c34b37d1d6251bcb52afb35 to your computer and use it in GitHub Desktop.
Save adamrosloniec/7cbd29554c34b37d1d6251bcb52afb35 to your computer and use it in GitHub Desktop.
JavaScript - In Object - Find Keys with same prefix
var obj = {
online_rate_1: "$5.00",
online_rate_2: "$22.00",
online_rate_3: "$44.00",
rate_1: "$9.00",
rate_2: "$18.00",
rate_3: "$30.00",
rate_description: "<p>Some description text</p>",
time_period_1: "0 - 0.5 Hours",
time_period_2: "0.5 - 1 Hours",
time_period_3: "1 - 2 Hours",
}
function findKeysWithPrefix(object, prefix) {
var arr = [];
for ( var property in object) {
if (
object.hasOwnProperty(property)
&& property.toString().startsWith(prefix)
&& /\d/.test(property.toString())
) {
arr.push(object[property]);
}
}
return arr;
}
console.log( findKeysWithPrefix( obj, 'online' ) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment