简体   繁体   English

如何使用 AngularJS 从提取的 JSON object 属性中解析数据?

[英]How to parse data from an extracted JSON object property using AngularJS?

I have a JSON object property that is a string and looks like this:我有一个 JSON object 属性,它是一个字符串,如下所示:

"&1 *UBIN 8 &2 *UBIN 8 &3 *UBIN 8 &4 *CHAR 10 &5 *UBIN 8 &6 *UBIN 8 &7 *UBIN 8 &8 *CCHAR *VARY 4"

I want to parse this property (string) to extract the numbers that have an & (ampersand) in front of them, and place each extracted &number into an array.我想解析这个属性(字符串)以提取前面有 & (与号)的数字,并将每个提取的 &number 放入一个数组中。 The result would look like:结果将如下所示:

var array = ['&1', '&2', '&3', '&4', '&5', '&6', '&7', '&8'];

I am using AngularJS.我正在使用 AngularJS。

Any suggestions on how to best accomplish this?关于如何最好地做到这一点的任何建议?

try this尝试这个

var str="&1 *UBIN 8 &2 *UBIN 8 &3 *UBIN 8 &4 *CHAR 10 &5 *UBIN 8 &6 *UBIN 8 &7 *UBIN 8 &8 *CCHAR *VARY 4";

var result = $.map(str.split(" "), function(element) {
  if ( element.substring(0,1)  == "&") return element;
});

result结果

["&1","&2","&3","&4","&5","&6","&7","&8"]

The algorithm for this would be "split() and filter()".用于此的算法将是“split() 和 filter()”。

A naive approach could check if the first character is an ampersand:一种天真的方法可以检查第一个字符是否是 & 符号:

input = "&1 *UBIN 8 &2 *UBIN 8 &3 *UBIN 8 &4 *CHAR 10 &5 *UBIN 8 &6 *UBIN 8 &7 *UBIN 8 &8 *CCHAR *VARY 4"

input.split(" ").filter(item => item.startsWith("&"))

This works well and is fast, but makes the assumption that only numbers can come after & , so it will also return items like &abc .这很好用而且速度很快,但假设只有数字可以在&之后,所以它也会返回&abc之类的项目。

You could also use a regex:您还可以使用正则表达式:

input.split(" ").filter(item => item.match(/^&\d+$/))

This is slower, but it's more robust.这速度较慢,但更健壮。 It also makes the assumption that only full-number items are allowed, so it will reject items like &12a .它还假设只允许全数项目,因此它将拒绝&12a之类的项目。

Both solutions can be adapted if the full list of requirements differ, as from the question is not fully clear if:如果完整的要求列表不同,则可以调整两种解决方案,因为如果以下情况不完全清楚,则问题:

  • the separator is space, or it can be other characters (eg comma, or newline, or tab)分隔符是空格,也可以是其他字符(例如逗号、换行符或制表符)
  • items starting with & are known to contain only numbers, or can contain other characters too&开头的项目已知只包含数字,或者也可以包含其他字符
  • negative numbers are considered valid or not负数被认为是有效的或无效的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM