-4

I have this JSON:

[
  { someTitle: 'NAME OF SomeTitle' },
  [
    {
      id: '7oiqxhRXRqEV0D70G',
      photo: 'https://co/image/ab67616d739a3e7d0c38c3af225e4695ce',
      jugement: 'GOAl',
      Name: 'Some Name.'
    }
  ],
  {
    token: 'BQAVhYiUweHGTTlIIZHthAKzulZ-DHg'
  }
]

This comes from a request I make to my node Server. If I do a console.log(req.body) I get the information above. So when I try to do console.log(req.body.token) I get undefined. How can I access the token property then? The size of the JSON may change , so I can't just access it by index.

ErFran
  • 1
  • 3

2 Answers2

1

Since it is an array of objects, and the element you are looking for is at the 3th position of the array. You need to call it using index = 2 (because index starts with 0). After that, you can access token property.

const res = [{
    someTitle: 'NAME OF SomeTitle'
  },
  [{
    id: '7oiqxhRXRqEV0D70G',
    photo: 'https://co/image/ab67616d739a3e7d0c38c3af225e4695ce',
    jugement: 'GOAl',
    Name: 'Some Name.'
  }],
  {
    token: 'BQAVhYiUweHGTTlIIZHthAKzulZ-DHg'
  }
]

console.log(res[2].token)
holydragon
  • 6,158
  • 6
  • 39
  • 62
  • Hey Sorry! I forgot to mentioned that the JSON won't be always the same size, so I can't access it by Index – ErFran Jun 10 '20 at 04:15
  • @ErFran At First, you should structure your JSON Properly. If you can't access it by index you have to loop through the JSON objects, for that, a proper JSON structure is needed. – Harish ST Jun 10 '20 at 04:23
0

Check this out

console.log(req.body[2]["token"])

If Array size is not fixed then try this

let req = {
  body: [
    { someTitle: "NAME OF SomeTitle" },
    [
      {
        id: "7oiqxhRXRqEV0D70G",
        photo: "https://co/image/ab67616d739a3e7d0c38c3af225e4695ce",
        jugement: "GOAl",
        Name: "Some Name.",
      },
    ],
    {
      token: "BQAVhYiUweHGTTlIIZHthAKzulZ-DHg",
    },
  ],
};

let data = req.body;
let token = "";
for (let each of data) {
  if (each.hasOwnProperty("token")) {
    token = each["token"];
    break;
  }
}
console.log(token)

utkarshp64
  • 16
  • 1
  • 4