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

JavaScript高级数组操作:按情绪标签分组猫咪数据的实现问题

问题:按情绪标签分组猫咪图片数据

原始数据

const catsData = [
    {
        emotionTags: ["moody"],
        isGif: false,
        image: "angry.jpeg",
        alt: "A cat looking moody",
    },
    {
        emotionTags: ["moody", "insomniac"],
        isGif: false,
        image: "angry2.jpeg",
        alt: "A cat looking moody",
    },
    {
        emotionTags: ["moody"],
        isGif: false,
        image: "angry3.jpeg",
        alt: "A cat looking moody",
    },
    {
        emotionTags: ["confused", "sad"],
        isGif: false,
        image: "confused.jpeg",
        alt: "A cat looking confused",
    }
];

需求说明

需要将上述数组转换为按emotionTags单标签分组的数组:

  • 每个分组包含单个情绪标签、isGif属性、对应情绪的image数组和alt数组
  • 带有多个情绪标签的条目,需归入每个对应情绪的分组

尝试的错误代码

let emotions = ['moody','insomniac','confused','sad','dominant','hungry','relaxed','angry']

let modCatData = catsData.reduce((allCat, cat,idx)=>{
  let imageArr = []
  if(cat['emotionTags'].includes (emotions[idx])){
    imageArr.push(cat.image)
    allCat.push({
      'image':imageArr
    })
  }
  else{
    allCat.push({
      'image':cat.image
    })
  }
  return allCat
  
},[])

console.log(modCatData)

正确实现方案

核心思路

  1. 用reduce创建临时映射对象,以情绪标签为键、对应分组对象为值,快速查找和更新分组
  2. 遍历每一条猫咪数据,再遍历其所有情绪标签
  3. 若当前标签未创建分组,初始化分组结构;若已存在,直接将当前猫咪的image和alt添加到对应数组
  4. 最后将映射对象的取值转换为数组,得到目标格式

实现代码

const catsData = [
    {
        emotionTags: ["moody"],
        isGif: false,
        image: "angry.jpeg",
        alt: "A cat looking moody",
    },
    {
        emotionTags: ["moody", "insomniac"],
        isGif: false,
        image: "angry2.jpeg",
        alt: "A cat looking moody",
    },
    {
        emotionTags: ["moody"],
        isGif: false,
        image: "angry3.jpeg",
        alt: "A cat looking moody",
    },
    {
        emotionTags: ["confused", "sad"],
        isGif: false,
        image: "confused.jpeg",
        alt: "A cat looking confused",
    }
];

const groupedCats = Object.values(catsData.reduce((acc, cat) => {
    // 遍历当前猫咪的所有情绪标签
    cat.emotionTags.forEach(tag => {
        // 初始化分组(如果不存在)
        if (!acc[tag]) {
            acc[tag] = {
                emotionTags: tag,
                isGif: cat.isGif,
                image: [],
                alt: []
            };
        }
        // 将当前猫咪的图片和描述加入对应分组
        acc[tag].image.push(cat.image);
        acc[tag].alt.push(cat.alt);
    });
    return acc;
}, {}));

console.log(groupedCats);

补充说明

如果需要避免同一image在分组中重复出现,可以在push前增加判断:

// 替换原push代码
if (!acc[tag].image.includes(cat.image)) {
    acc[tag].image.push(cat.image);
    acc[tag].alt.push(cat.alt);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 22:00:35