Vue.js/JavaScript中如何将目标数组转换为嵌套数值数组?
正确实现方法
你的代码存在两个关键问题:
forEach方法没有返回值,计算属性最终会返回undefined- 原数组中的属性是
Points(首字母大写),但你代码里写成了小写的points,导致无法正确遍历
以下是两种可行的实现方式:
方法一:使用flatMap(推荐)
flatMap会先对每个元素执行map转换,再将结果扁平一层,刚好匹配需求:
computed: { departureStops() { return this.stops.flatMap(stop => stop.Points.map(point => [point.Lat, point.Lon]) ); } }
方法二:使用reduce(兼容旧环境)
如果运行环境不支持flatMap,可以用reduce手动合并数组:
computed: { departureStops() { return this.stops.reduce((total, stop) => { const convertedPoints = stop.Points.map(point => [point.Lat, point.Lon]); return total.concat(convertedPoints); }, []); } }
两种方法都能将原数组转换为你需要的[[2,3], [4,5], [6,7], [8,9]]格式。
内容的提问来源于stack exchange,提问作者bob
相关产品推荐
相关产品推荐

