2

I have scraped this object using puppeteer but it contains more information than I actually need. How do I access "height" within "components"? I have been googling for a while and have not found a solution that works.

{
  "components": [{
    "height": "1.8",
    "period": 11,
    "trueDirection": 139,
    "compassDirection": "SE"
  }, {
    "height": "5.5",
    "period": 8,
    "trueDirection": 72,
    "compassDirection": "ENE"
  }, {
    "height": "1",
    "period": 13,
    "trueDirection": 207,
    "compassDirection": "SSW"
  }],
  "unit": "ft",
  "title": "2-3<small class=\"unit\">ft</small>\n",
  "fadedRating": 0,
  "solidRating": 1,
  "time": "Noon",
  "date": "Thu 14/02",
  "isBigWave": false
}
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Sokushinbutsu
  • 83
  • 1
  • 5

2 Answers2

2

To extract an array containing all the height values, use map like so:

const data = {
  "components": [{
    "height": "1.8",
    "period": 11,
    "trueDirection": 139,
    "compassDirection": "SE"
  }, {
    "height": "5.5",
    "period": 8,
    "trueDirection": 72,
    "compassDirection": "ENE"
  }, {
    "height": "1",
    "period": 13,
    "trueDirection": 207,
    "compassDirection": "SSW"
  }],
  "unit": "ft",
  "title": "2-3<small class=\"unit\">ft</small>\n",
  "fadedRating": 0,
  "solidRating": 1,
  "time": "Noon",
  "date": "Thu 14/02",
  "isBigWave": false
};

const heights = data.components.map(e => e.height);

console.log(heights);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
1

Here I use .forEach to iterate through the components array then you can access each height easily.

const obj = {
  "components": [{
    "height": "1.8",
    "period": 11,
    "trueDirection": 139,
    "compassDirection": "SE"
  }, {
    "height": "5.5",
    "period": 8,
    "trueDirection": 72,
    "compassDirection": "ENE"
  }, {
    "height": "1",
    "period": 13,
    "trueDirection": 207,
    "compassDirection": "SSW"
  }],
  "unit": "ft",
  "title": "2-3<small class='\\unit\\'>ft</small>\\n",
  "fadedRating": 0,
  "solidRating": 1,
  "time": "Noon",
  "date": "Thu 14/02",
  "isBigWave": false
}

obj.components.forEach(c => console.log(c.height)) 
holydragon
  • 6,158
  • 6
  • 39
  • 62