Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through object get value using regex key matches Javascript

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

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

like image 309
vetri02 Avatar asked May 25 '12 16:05

vetri02


2 Answers

Yes, sure you can. Here's how:

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

This was the regex way, but for simple stuff, you may want to 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 want values of all the attributes, you may use an array to store those attributes, match them using regex/indexOf - whatever convenient - and do something with those values...I'd leave this task to you.

like image 145
Parth Thakkar Avatar answered Nov 01 '22 16:11

Parth Thakkar


You can sidestep the entire 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 regex, you can easily loop through the array by varying the array index:

for (var i=0; i<obj.people.length; i++) {
    var fname = obj.people[i].fname;
    // do something with fname
}
like image 21
Blazemonger Avatar answered Nov 01 '22 16:11

Blazemonger