Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JS. How to collect each required element from an array

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

print "hello world"
var msg = "secret message"

Can you help me, I don’t know how to do this.

>Solution :

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);});

e.g.:

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);});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading