I am making a tokenizer that builds an abstract tree and I want to collect all the "text" from an array that is output by my tokenizer.
Output:
{
"error": false,
"tokens": [
{
"type": "keyword",
"value": "print",
"text": "print"
},
{
"type": "string",
"value": "hello world",
"text": "hello world"
},
{
"type": "keyword",
"value": "var",
"text": "var"
},
{
"type": "keyword_valueof",
"value": "msg",
"text": "msg"
},
{
"type": "operator",
"value": "eq",
"text": "="
},
{
"type": "string",
"value": "secret message",
"text": "secret message"
}...
It should turn out like this:
print "hello world"
var msg = "secret message"
Can you help me, I don't know how to do this.
If you want to extract each value of the "text" to an array, you can use the map() method:
const arr = obj.tokens.map((token) => token.text);
Where 'obj' is the main object (with the "errors" and "tokens" keys).
To print each element of the array in a new line:
arr.forEach(elem => {console.log(elem);});
eg:
const obj = { "error": false, "tokens": [ { "type": "...", "value": "...", "text": "text 1" }, { "type": "...", "value": "...", "text": "text 2" } ] } const tokensArr = obj.tokens.map(token => token.text); tokensArr.forEach(elem => {console.log(elem);});
Is this what you're looking for?
let array = ["secretMessage", "anotherMessage"]; //The array let theNumberIdOfMessage = 0; //The first item of the array console.log(array[theNumberIdOfMessage]); //Get the item first in the array and log it theNumberIdOfMessage = 1; //The second item of the array console.log(array[theNumberIdOfMessage]); //Log the second item
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.