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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With