使用正则表达式键匹配对象遍历对象获取值 [英] Loop through object get value using regex key matches Javascript

查看:119
本文介绍了使用正则表达式键匹配对象遍历对象获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

具有这样的对象.我可以在诸如Fname *,Lname *之类的键上使用正则表达式获取值并获取值.

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]
}

这是正则表达式的方式,但是对于简单的东西,您可能需要使用indexOf().如何?方法如下:

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]
}

如果您想使用属性列表来做某事,我的意思是您想要所有属性的值,则可以使用数组来存储这些属性,使用regex/indexOf匹配它们-方便的话-并做一些这些值...我会把这个任务留给你.

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.

这篇关于使用正则表达式键匹配对象遍历对象获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆