'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:
"&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. The result would look like:
var array = ['&1', '&2', '&3', '&4', '&5', '&6', '&7', '&8'];
I am using AngularJS.
Any suggestions on how to best accomplish this?
Solution 1:[1]
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"]
Solution 2:[2]
The algorithm for this would be "split() and 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.
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.
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 (e.g. 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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Cristik |
