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

如何根据条件聚合对象数组,生成指定格式的renderData?

数据分组转换问题解决方案

问题背景

现有一个名为tags的对象数组,结构如下:

const tags = [
    {
        "tagId": 12,
        "value": 24.2,
        "time": "2022-10-12T02:00:00Z"
    },
    {
        "tagId": 12,
        "value": 25,
        "time": "2022-10-12T06:00:00Z"
    },
    {
        "tagId": 12,
        "value": 28,
        "time": "2022-10-12T09:00:00Z"
    },
    {
        "tagId": 13,
        "value": 23,
        "time": "2022-10-12T02:00:00Z"
    },
    {
        "tagId": 13,
        "value": 23.5,
        "time": "2022-10-12T06:00:00Z"
    },
    {
        "tagId": 13,
        "value": 23.3,
        "time": "2022-10-12T09:00:00Z"
    },
    {
        "tagId": 14,
        "value": 24,
        "time": "2022-10-12T02:00:00Z"
    },
    {
        "tagId": 14,
        "value": 25.4,
        "time": "2022-10-12T06:00:00Z"
    },
    {
        "tagId": 14,
        "value": 26.4,
        "time": "2022-10-12T09:00:00Z"
    },
];

定义变量Atempid = 12、Ahumid = 13、groundtemp = 14,需要将tags处理为指定格式的renderData:将相同tagId对应的value合并为数组,根据tagId与上述变量的匹配关系,分别设置label、borderColor、backgroundColor字段,预期结果如下:

const renderData = [
    {
        "label": "temp",
        "data": [24.2,25,28],
        "borderColor": "red",
        "backgroundColor": "red"
    },
    {
        "label": "hum",
        "data": [23,23.5,23.3],
        "borderColor": "orange",
        "backgroundColor": "orange"
    },
    {
        "label": "groundtemp",
        "data": [24,25.4,26.4],
        "borderColor": "yellow",
        "backgroundColor": "yellow"
    }
];

此前使用map方法编写的代码会让每个元素单独成为一个对象,不符合预期,需修改代码实现需求。

解决方案

问题原因

map方法会遍历数组中的每一个元素并返回一个新元素,因此直接用map处理tags会生成9个独立对象,无法实现按tagId分组合并的效果。需要先对数据进行分组,再转换为目标格式。

实现步骤

  1. 创建tagId与配置信息(标签、颜色)的映射表,方便后续快速查找;
  2. 使用reduce方法遍历tags数组,按tagId分组收集对应的value数组;
  3. 将分组后的结果转换为预期的renderData格式。

代码示例

// 定义tagId对应的配置信息
const tagConfig = {
    [12]: { label: 'temp', color: 'red' },
    [13]: { label: 'hum', color: 'orange' },
    [14]: { label: 'groundtemp', color: 'yellow' }
};

// 第一步:按tagId分组,收集对应value数组
const groupedData = tags.reduce((acc, item) => {
    const { tagId, value } = item;
    // 如果当前tagId还未在分组对象中,初始化空数组
    if (!acc[tagId]) {
        acc[tagId] = [];
    }
    // 将当前value推入对应tagId的数组
    acc[tagId].push(value);
    return acc;
}, {});

// 第二步:将分组数据转换为目标格式
const renderData = Object.entries(groupedData).map(([tagId, data]) => {
    const { label, color } = tagConfig[tagId];
    return {
        label,
        data,
        borderColor: color,
        backgroundColor: color
    };
});

console.log(renderData);

代码说明

  • reduce方法负责将相同tagId的value聚合到同一个数组中,生成一个以tagId为键、value数组为值的对象;
  • Object.entries将分组对象转换为键值对数组,再通过map方法将每个键值对转换为符合预期格式的对象,从tagConfig中取出对应的标签和颜色信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 19:35:23