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

如何基于属性对JavaScript数组分组,将text匹配对应line集合

JavaScript对象数组转换方案

实现思路

  • 先构建临时映射关系存储text和对应的line集合,避免text重复创建对象
  • 两层遍历原数组:外层遍历拿到每个line值,内层遍历该line关联的所有text值,将line值存入对应text的集合中
  • 最后将映射关系转换为要求的数组结构即可

代码实现

基础写法(兼容性好)

var myArray = [
  { line: 20, text: [31, 80] },
  { line: 10, text: [80, 22] }
]

// 临时存储text与对应line的映射
const tempMap = {}
myArray.forEach(item => {
  const currentLine = item.line
  // 遍历当前line对应的所有text值
  item.text.forEach(textVal => {
    if (!tempMap[textVal]) {
      tempMap[textVal] = []
    }
    tempMap[textVal].push(currentLine)
  })
})

// 映射转目标数组
const myNewArray = Object.entries(tempMap).map(([text, line]) => ({
  text: Number(text), // 转数字匹配原数据类型
  line
}))

ES6+ 简洁写法

使用Map作为临时存储,不需要额外处理text的类型转换:

const tempMap = new Map()
myArray.forEach(item => {
  const currentLine = item.line
  item.text.forEach(textVal => {
    if (!tempMap.has(textVal)) {
      tempMap.set(textVal, [])
    }
    tempMap.get(textVal).push(currentLine)
  })
})

const myNewArray = Array.from(tempMap, ([text, line]) => ({ text, line }))

如果需要line数组按数字大小排序,可以在存入时或者转换时增加排序逻辑,示例:

// 转换时排序
const myNewArray = Array.from(tempMap, ([text, line]) => ({ 
  text, 
  line: line.sort((a, b) => a - b) 
}))

内容的提问来源于stack exchange,提问作者Ali Haghighi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 09:42:02