简体   繁体   中英

JSON array items return undefined

I'm taking an array from a JSON object and iteratting through each item of the children array to create a new array with the id and name of each child. However, when trying to use the.id or.name, undefined is returned resulting in a blank array.

const functions = require('firebase-functions');

const cors = require('cors')({ origin: true });

const cheerio = require('cheerio');
const getUrls = require('get-urls');
const fetch = require('node-fetch');

const scrapeteamtags = (text) => {
    const urls = Array.from( getUrls(text) );
    const requests = urls.map(async url => {

        const res = await fetch(url);
        const html = await res.text();
        const $ = cheerio.load(html);
        
        const getTeamlist = JSON.parse($('body').text())  
        
        var teams = {
            newgames: []
        }

        getTeamlist.SSResponse.children.map(function(item) {
            teams.newgames.push({   
                "event-id": item.event.id
            });            
            console.log(teams.newgames)
        })
        
        console.log(teams.newgames[0])

        return {
            teams
            //"game": getTeamlist.SSResponse.children[0].event.name
        }
    });
    
    return Promise.all(requests);
}

exports.scraper = functions.https.onRequest( async (request, response) => {
    cors(request, response, async () => {

        const body = (request.body);
        const data = await scrapeteamtags(body.text);

        response.send(data)

    });
});

the JSON object (actual object contains many items in children array):

{
"SSResponse":{
   "xmlns":"http://schema.openbet.com/SiteServer/2.31/SSResponse.xsd",
   "children":[
      {
         "event":{
            "id":"230526710",
            "name":"Sevilla v Real Valladolid",
            "children":[
               {
                  "market":{
                     "id":"452880267",
                     "eventId":"230526710",
                     "children":[
                        {
                           "outcome":{
                              "id":"1080419229",
                              "marketId":"452880267",
                              "name":"Draw",
                              "children":[
                                 {
                                    "price":{
                                       "id":"1",
                                       "priceDec":"4.25"
                                }}]}},
                        {
                           "outcome":{
                              "id":"1080419232",
                              "marketId":"452880267",
                              "name":"Sevilla",
                              "children":[
                                 {
                                    "price":{
                                       "id":"2",                                    
                                       "priceDec":"1.40"
                                }}]}},
                        {
                        "outcome":{
                            "id":"1080419233",
                            "marketId":"452880267",
                            "name":"Real Valladolid",                                  
                            "children":[
                                {
                                "price":{
                                    "id":"3",
                                    "priceDec":"9.50"
                                }}]}}]}}]}},
      {
         "responseFooter":{
            "cost":"238",
            "creationTime":"2020-06-26T17:04:39.617Z"
        }}]}}

the parts of the array that are of interest to me are the id and name of the first child, then of the nested child objects the id and 'priceDec', initally I am just trying to add the first id to an array and then work on getting the next children objects. Thanks

Having this code:

getTeamlist.SSResponse.children.map(function(item) {
      teams.newgames.push({   
          "event-id": item.event.id
      });            
      console.log(teams.newgames)
  })

All the childrens inside SSResponse key do not have an event key, that is why you get undefined , try this inside the map function:

if(Object.keys(item).includes('event')){
      teams.newgames.push({   
          "event-id": item.event.id,
          "event-name": item.event.name
      });
    }

Basically asking for a key named "event" and then get the data. You can check this link of stackblitz for an example. Hope this help you!

Hi Ethan as far as accessing the fields in the object and the array are concerned you can try. You can simply use the. operator as follow: outcome.id or outcome.name and for the child array you can use: outcome.children[0].price.id

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM