【问题标题】:Access elements of array within object [duplicate]访问对象内数组的元素[重复]
【发布时间】:2019-07-02 06:15:27
【问题描述】:

我已经使用 puppeteer 抓取了这个对象,但它包含的信息比我实际需要的要多。如何访问“组件”中的“高度”?我已经在谷歌上搜索了一段时间,但没有找到有效的解决方案。

{
  "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
}

【问题讨论】:

  • 你当前提取height的代码是什么?

标签: javascript arrays json object ecmascript-6


【解决方案1】:

这里我使用 .forEach 遍历组件数组,然后您可以轻松访问每个高度。

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

【讨论】:

    【解决方案2】:

    要提取包含所有height 值的数组,请像这样使用map

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-27
      • 1970-01-01
      • 1970-01-01
      • 2016-02-02
      • 1970-01-01
      • 2020-09-19
      • 2014-06-10
      相关资源
      最近更新 更多