Loop through object to get value using regex key matches javascript

var obj = { Fname1: "John", Lname1: "Smith", Age1: "23", Fname2: "Jerry", Lname2: "Smith", Age2: "24" } 

with such an object. Can I get the value using regex on the key something like Fname *, Lname * and get the values.

+7
source share
5 answers

Oh sure. Here's how:

 for(var key in obj) { if(/^Fname/.test(key)) ... do something with obj[key] } 

It was a regex, but for simple things you can use indexOf() . How? Here's how:

 for(var key in obj) { if(key.indexOf('Fname') == 0) // or any other index. ... do something with obj[key] } 

And if you want to do something with a list of attributes, I mean that you need the values โ€‹โ€‹of all attributes, you can use an array to store these attributes, map them using regex / indexOf - no matter what is convenient - and do something with these meanings ... I would leave this task to you.

+15
source

You can get around the whole problem by using a more complete object instead:

 var objarr = [ {fname: "John", lname: "Smith", age: "23"}, {fname: "jerry", lname: "smith", age: "24"} ] ; objarr[0].fname; // = "John" objarr[1].age; // = "24" 

Or if you really need an object:

 var obj = { people: [ {fname: "John", lname: "Smith", age: "23"}, {fname: "jerry", lname: "smith", age: "24"} ]} ; obj.people[0].fname; // = "John" obj.people[1].age; // = "24" 

Now, instead of using a regular expression, you can easily loop through an array by changing the index of the array:

 for (var i=0; i<obj.people.length; i++) { var fname = obj.people[i].fname; // do something with fname } 
+6
source
 values = [] for(name in obj) { if (obj.hasOwnProperty(name) && name.test(/Fname|Lname/i) values[name] = obj[name]; } 
0
source

With jquery:

 $.each(obj, function (index,value) { //DO SOMETHING HERE WITH VARIABLES INDEX AND VALUE }); 
0
source

Key combination using include ()

I like the new includes feature. You can use it to check for 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 do not have ES2015 compilation, you can use

~key.indexOf(str)

0
source

All Articles