You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript如何将含坐标的对象数组转换为指定结构的新对象数组

解决方案

你只需要调整reduce回调中推入累加器的内容即可,不要仅推入坐标数组,而是推入符合预期结构的完整对象,修改后的代码如下:

const output = data.reduce((accumulator, curr) => {
  if(curr.Coordinates) {
    const coords = curr.Coordinates.map(({Lat, Long}) => [Lat, Long]);
    accumulator.push({
      name: curr.Name,
      coords: coords
    })
  };
  return accumulator;
}, []);

修改说明

  • 将内部处理坐标的变量从data改名为coords,避免和外层的原始数据变量data重名引发逻辑异常
  • 推入累加器的内容不再是纯坐标数组,而是包含name(取值为当前遍历项的Name属性)和coords属性的对象,完全匹配要求的输出结构
  • 会自动过滤无Coordinates属性的无效项(比如你原始数据中第一个没有坐标信息的对象不会被加入结果)

内容的提问来源于stack exchange,提问作者Sai Krishnadas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 08:36:04