如何基于对象时间字段映射数组生成嵌套数组结构?
如何将扁平化数组转换为按时间字段分组的嵌套数组?
你想要的效果完全可以通过嵌套的map函数实现,不用局限于只处理单个字段。核心思路是先确定要分组的时间字段列表,然后针对每个字段,遍历原数组生成对应的城市-时间对象数组。
直接实现方案(硬编码字段)
这是最直观的写法,适合字段固定的场景:
const list = [ { city: "new york", current_time: "123", time1: "456", time2: "789" }, { city: "london", current_time: "123", time1: "456", time2: "789" }, { city: "tokyo", current_time: "123", time1: "456", time2: "789" } ]; // 定义需要分组的时间字段顺序 const timeFields = ['current_time', 'time1', 'time2']; // 外层map遍历每个时间字段,内层map遍历每个城市生成目标对象 const result = timeFields.map(field => { return list.map(item => ({ city: item.city, time: item[field] })); }); console.log(result);
动态适配字段方案(无需硬编码)
如果以后可能新增time3、time4这类字段,可以动态提取时间字段(排除city字段),让代码更灵活:
const list = [ { city: "new york", current_time: "123", time1: "456", time2: "789" }, { city: "london", current_time: "123", time1: "456", time2: "789" }, { city: "tokyo", current_time: "123", time1: "456", time2: "789" } ]; // 自动提取所有非city的字段作为时间字段 const timeFields = Object.keys(list[0]).filter(key => key !== 'city'); const result = timeFields.map(field => list.map(item => ({ city: item.city, time: item[field] })) ); console.log(result);
关于forEach的替代写法
当然用forEach也能实现,但代码会稍显繁琐,因为需要手动创建数组并push元素:
const list = [ { city: "new york", current_time: "123", time1: "456", time2: "789" }, { city: "london", current_time: "123", time1: "456", time2: "789" }, { city: "tokyo", current_time: "123", time1: "456", time2: "789" } ]; const result = []; const timeFields = ['current_time', 'time1', 'time2']; timeFields.forEach(field => { const group = []; list.forEach(item => { group.push({ city: item.city, time: item[field] }); }); result.push(group); }); console.log(result);
对比下来,嵌套map的写法更简洁,也符合函数式编程的风格,推荐优先使用。
内容的提问来源于stack exchange,提问作者jando
相关产品推荐
相关产品推荐

