topojson/d3.js: Uncaught (in promise) TypeError: Cannot read property 'type' of undefined

topojson/d3.js: Uncaught (in promise) TypeError: Cannot read property 'type' of undefined

我正在尝试开发freeCodeCamp的第四个数据可视化认证项目,等值线图。这是我写的:

const promisses = [d3.json('https://raw.githubusercontent.com/no-stack-dub-sack/testable-projects-fcc/master/src/data/choropleth_map/counties.json'), d3.json('https://raw.githubusercontent.com/no-stack-dub-sack/testable-projects-fcc/master/src/data/choropleth_map/for_user_education.json')];

Promise.all(promisses).then((d)=>{return processData(d)});

function processData(data) {
  for (let i = 0; i < data.length; i++) {
    //console.log(JSON.stringify(data[i]));
  }
  
  let w = 800;
  let h = 0.6 * w;
  let padding = 40;
  
  let svg = d3.select('#chart-bg').append('svg');
  
  svg.attr('width', w + 2 * padding)
    .attr('height', h + 2 * padding)
    .attr('id','map')
  
  console.log(JSON.stringify(data[0].objects.counties));
  
  //The next line is where I am having trouble
  let counties = topojson.feature(data[0].objects.counties);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/topojson/3.0.2/topojson.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

直到最后一行都没有问题,但后来显示 "Uncaught (in promise) TypeError: Cannot read property 'type' of undefined"。有谁知道为什么会这样? data[0].objects.counties 正在正常记录。

编辑:data[0].objects.counties 有一个 'type' 属性 和一个 'geometries' 属性.

topojson.feature 有两个参数,如 topojson 文档中所示:

topojson.feature(topology, object);

您只指定了要提取的对象:

 let counties = topojson.feature(data[0].objects.counties);

错误可能源于缺少第二个参数:type 未定义第二个参数,因为未定义第二个参数。

使用这两个参数,您可以使用以下两个参数提取您的特征而不会出错:

let counties = topojson.feature(data[0], data[0].objects.counties);

const promisses = [d3.json('https://raw.githubusercontent.com/no-stack-dub-sack/testable-projects-fcc/master/src/data/choropleth_map/counties.json'), d3.json('https://raw.githubusercontent.com/no-stack-dub-sack/testable-projects-fcc/master/src/data/choropleth_map/for_user_education.json')];

Promise.all(promisses).then((d)=>{return processData(d)});

function processData(data) {
  for (let i = 0; i < data.length; i++) {
    //console.log(JSON.stringify(data[i]));
  }
  
  let w = 800;
  let h = 0.6 * w;
  let padding = 40;
  
  let svg = d3.select('#chart-bg').append('svg');
  
  svg.attr('width', w + 2 * padding)
    .attr('height', h + 2 * padding)
    .attr('id','map')
  
  
  //The next line is where I am having trouble
  let counties = topojson.feature(data[0], data[0].objects.counties);
  console.log(JSON.stringify(counties));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/topojson/3.0.2/topojson.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>