我如何从JSON对象数组中获取属性,以将该属性的值用作图表中的标签?

问题描述 投票:0回答:1

我正在尝试使用chart.js库绘制图表。我目前正在尝试绘制json文件的数据。

这是我能够获取部门和国家/地区属性值的代码。

const xs = [];
const ys = [];
const api_url = 'jsondata.json';

async function getData() {
  const response = await fetch(api_url);
  const data = await response.json();
  const sector = data.map(prop => prop.sector);
  xs.push(sector);
  console.log(sector);
  const country = data.map(prop => prop.country);
  xs.push(country);
  console.log(country);
}

getData();

我的JSON文件看起来像这样:

[{
    "end_year": "",
    "intensity": 6,
    "sector": "Energy",
    "published": "January, 09 2017 00:00:00",
    "country": "United States of America",
  },
  {
    "end_year": "",
    "intensity": 6,
    "sector": "Energy",
    "published": "January, 09 2017 00:00:00",
    "country": "United States of America",
  }
]

我正在尝试获取这些属性的值,并将它们分别用作x轴和y轴的标签。

javascript json chart.js fetch-api
1个回答
0
投票

如果我理解正确,那是你的答案

let json = [{
    "end_year": "",
    "intensity": 6,
    "sector": "Energy",
    "published": "January, 09 2017 00:00:00",
    "country": "United States of America",
  },
  {
    "end_year": "",
    "intensity": 6,
    "sector": "Two",
    "published": "January, 09 2017 00:00:00",
    "country": "Canada",
  }
];

let sectors = json.map((obj) => {
  return obj.sector
})
let countries = json.map((obj) => {
  return obj.country
})
console.log('sectors:', sectors)
console.log('countries:', countries)
© www.soinside.com 2019 - 2024. All rights reserved.