Home > Back-end >  JS. How to collect each required element from an array
JS. How to collect each required element from an array

Time:08-26

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.

CodePudding user response:

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

CodePudding user response:

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

  • Related