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
  • 67,454
  • 15
  • 130
  • 155
vetri02
  • 3,199
  • 8
  • 32
  • 43

5 Answers5

20

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,427
  • 3
  • 25
  • 34
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
  • 90,923
  • 26
  • 142
  • 180
0
values = []
for(name in obj) {
   if (obj.hasOwnProperty(name) && name.test(/Fname|Lname/i) values[name] = obj[name];
}
agent-j
  • 27,335
  • 5
  • 52
  • 79
0

With jquery:

$.each(obj, function (index,value) {
    //DO SOMETHING HERE WITH VARIABLES INDEX AND VALUE
});
John Shepard
  • 937
  • 1
  • 9
  • 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,839
  • 5
  • 31
  • 51
Ralph Cowling
  • 2,839
  • 1
  • 20
  • 10