javascript通过使用Regex匹配键从JSON对象检索值 [英] javascript retrieve value from JSON object by matching key using Regex

查看:80
本文介绍了javascript通过使用Regex匹配键从JSON对象检索值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下javascript对象文字(摘录)

I have the following javascript object literal (excerpt)

var foo = {"hello[35]":100,"goodbye[45]":42};

我有以下查询:

var query = "hello"

我想打电话给foo [查询]获取值100,但有一个[35]我不一定知道它的值。我确信我会得到一个独特的比赛。有没有办法输入查询是某种javascript正则表达式?即

I would like to call foo[query] to obtain the value 100, but there is a [35] for which I don't necessarily know the value of. I know for sure that I will get a unique match. Is there any way to input query is some kind of javascript regular expression? i.e.

Regex = /hello/
foo[Regex]
100

原谅noob问题......

pardon the noob question...

推荐答案

你在这里有什么:

var foo = {"hello[35]":100,"goodbye[45]":42};

不是 JSON,它是对象的字符串表示形式;你有一个对象文字,它创建一个实际的JavaScript对象。据我所知,通过将属性名称与正则表达式匹配来从对象中检索值的唯一方法是枚举属性名称并测试每个属性名称。您需要的正则表达式如下:

is not JSON, which is a string representation of an object; what you have is an object literal, which creates an actual JavaScript object. As far as I know the only way to retrieve a value from an object by matching a property name with a regex is to enumerate the property names and test each one. The regex you'll need is something like:

/^hello(\[\d*\])?$/

...将与hello匹配,可选地后跟零或更多位数括号。但是你不想硬编码你好,因为你也(大概)需要再见值,所以使用一个函数:

...which will match against "hello" optionally followed by zero or more digits in square brackets. But you don't want to hard code "hello" given that you also (presumably) need the "goodbye" value, so use a function:

function getPropertyByRegex(obj,propName) {
   var re = new RegExp("^" + propName + "(\\[\\d*\\])?$"),
       key;
   for (key in obj)
      if (re.test(key))
         return obj[key];
   return null; // put your default "not found" return value here
}

var foo = {"hello[35]":100,"goodbye[45]":42};

alert(getPropertyByRegex(foo, "hello"));    // 100
alert(getPropertyByRegex(foo, "goodbye"));  // 42
alert(getPropertyByRegex(foo, "whatever")); // null (not found)

演示: http://jsfiddle.net/asDQm/

这篇关于javascript通过使用Regex匹配键从JSON对象检索值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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