Laravel 8视图中转换JavaScript对象数组为D3可视化格式时出现TypeError问题求助
Laravel 8视图中转换JavaScript对象数组为D3可视化格式时出现TypeError问题求助
嗨,我来帮你排查这个问题~你遇到的Uncaught TypeError: Cannot set properties of undefined (setting 'location_id')错误,根源其实很简单:
你初始化了一个空数组vis,但在循环里直接尝试给vis[x]['location_id']赋值——这时候vis[x]还没有被定义成一个对象,它的值是undefined,自然没法给它设置属性。
先给你修复基础版本的代码
只需要在给vis[x]的属性赋值前,先创建一个空对象就行,另外还要注意你目标数组里的键名是name和total,不是原数据的location_id和count,我一起帮你修正了:
console.log('All the items are here:', items) const colors = ["red", "yellow", "green", "blue"]; const vis = []; if (items.length) { console.log(items[0].location_id) let x = 0; for( let i=0; i<items.length; i++){ console.log(items[i].location_id); if (items[i].location_id !== undefined) { console.log('i = ', i); console.log('First location id = ', items[i].location_id); // 关键:先创建一个空对象存入数组对应的位置 vis[x] = {}; // 对应目标数组的键名 vis[x]['name'] = items[i].location_id; vis[x]['total'] = items[i].count; // 用colors的长度判断更灵活,避免硬编码5 if(x < colors.length) { // 这里用x而不是i,因为x是有效项的索引,避免跳过项时颜色对应错误 vis[x]['color'] = colors[x]; } else { vis[x]['color'] = "red"; } x++; } } } else { console.log('there are no items') } console.log('Visitors new array: ', vis)
更简洁的写法(推荐)
其实处理这种数组转数组的场景,用JavaScript的filter+map方法会更简洁易读,不用手动管理索引:
console.log('All the items are here:', items) const colors = ["red", "yellow", "green", "blue"]; // 先过滤掉没有location_id的项,再把每个有效项映射成你需要的格式 const vis = items .filter(item => item.location_id !== undefined) .map((item, index) => ({ name: item.location_id, total: item.count, color: index < colors.length ? colors[index] : "red" })); console.log('Visitors new array: ', vis)
另外顺便说一句:你看到的[[Prototype]]:Array(0)只是数组的原型指向空数组,不代表你的原数组是空的——你的数组确实有3个元素,这是浏览器控制台的正常显示,不用在意~
备注:内容来源于stack exchange,提问作者DavidN
相关产品推荐
相关产品推荐

