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

Vue.js中如何聚合Node.js API返回的重复人员多语言数据?

数据聚合实现方案

你可以在Vue的请求回调中,通过Array.reduce()方法对返回的原始数据进行分组聚合,将同一人员的多条语言信息合并到Idiomas数组中。

修改后的Vue代码

export default {
  el: "myFormPerson",
  data() {
    return {
      results: [],
      ced: '',
    }
  },
  methods: {
    submitForm() {
      axios.get('http://localhost:8080/person/' + this.ced)
        .then((response) => {
          // 对原始数据进行聚合处理
          this.results = this.aggregatePersonData(response.data);
        })
        .catch(function (error) {
          console.log(error);
        })
        .finally(function () {});
    },
    // 定义数据聚合方法
    aggregatePersonData(rawData) {
      // 使用reduce分组,以人员Id为唯一标识
      const groupedData = rawData.reduce((accumulator, currentItem) => {
        const personId = currentItem.Id;
        // 如果当前人员未在分组中,初始化基础信息和语言数组
        if (!accumulator[personId]) {
          accumulator[personId] = {
            Id: currentItem.Id,
            ced: currentItem.ced,
            Name: currentItem.Name,
            Idiomas: []
          };
        }
        // 提取当前条目里的语言信息,加入到对应人员的Idiomas数组
        accumulator[personId].Idiomas.push({
          NativeLanguage: currentItem.NativeLanguage,
          Level: currentItem.Level,
          NameLang: currentItem.NameLang
        });
        return accumulator;
      }, {});
      // 将分组后的对象转换为数组格式
      return Object.values(groupedData);
    }
  },
}

代码说明

  1. 数据分组逻辑:通过reduce遍历原始数据,以人员的Id作为分组键,确保同一人员的信息被合并到同一个对象中。
  2. 基础信息初始化:首次遇到某一人员时,创建包含Id、ced、Name以及空Idiomas数组的对象。
  3. 语言信息聚合:将每条数据中的语言相关字段(NativeLanguage、Level、NameLang)提取出来,添加到对应人员的Idiomas数组中。
  4. 格式转换:最后将分组后的对象转换为数组,得到你需要的嵌套结构数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 19:01:21