Loop through object get value using regex key matches Javascript

后端 未结 5 1426
一整个雨季
一整个雨季 2021-01-04 11:15
var obj = {
 Fname1: \"John\",
 Lname1: \"Smith\",
 Age1: \"23\",
 Fname2: \"Jerry\",
 Lname2: \"Smith\",
 Age2: \"24\"
}

with an object like this.

5条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-04 12:04

    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.

提交回复
热议问题