12
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.

Claudio Redi
  • 65,896
  • 14
  • 126
  • 152
vetri02
  • 3,029
  • 7
  • 31
  • 42

5 Answers5

18

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.

Parth Thakkar
  • 5,309
  • 3
  • 23
  • 33
7

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
}
Blazemonger
  • 86,267
  • 25
  • 136
  • 177
0
values = []
for(name in obj) {
   if (obj.hasOwnProperty(name) && name.test(/Fname|Lname/i) values[name] = obj[name];
}
agent-j
  • 26,389
  • 5
  • 49
  • 78
0

With jquery:

$.each(obj, function (index,value) {
    //DO SOMETHING HERE WITH VARIABLES INDEX AND VALUE
});
John Shepard
  • 927
  • 1
  • 7
  • 27
0

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)

JustCarty
  • 3,644
  • 5
  • 30
  • 49
Ralph Cowling
  • 2,819
  • 1
  • 18
  • 10