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

如何在Node.js/JavaScript中将扁平数组转为指定结构键值对对象数组

实现方案

思路说明

  • 原始数组为国家、年份交替排列的扁平化结构,首先按步长2遍历提取成对的国家与对应年份
  • 用临时对象做聚合容器,将同一国家的所有年份归集到同一数组下,同时将字符串格式的年份转换为数字类型
  • 最后将聚合结果转换为要求的对象数组,单夺冠年份直接返回数字,多夺冠年份返回数组

完整可运行代码

// 原始输入数组
const rawData = [
    "Spain",
    "2010",
    "Brazil",
    "1994",
    "Brazil",
    "1970",
    "Brazil",
    "1962",
    "Brazil",
    "2002",
    "Brazil",
    "1958",
    "Germany",
    "2014",
    "Germany",
    "1990",
    "Germany",
    "1974",
    "Germany",
    "1954",
    "Italy",
    "2006",
    "Italy",
    "1982",
    "Italy",
    "1938",
    "Italy",
    "1934",
    "France",
    "2018",
    "France",
    "1998",
    "Argentina",
    "1986",
    "Argentina",
    "1978",
    "Uruguay",
    "1930",
    "Uruguay",
    "1950",
    "England",
    "1966"
];

// 临时聚合对象
const countryMap = {};
// 按步长2遍历,每次取国家和对应年份
for (let i = 0; i < rawData.length; i += 2) {
    const countryName = rawData[i];
    const year = Number(rawData[i + 1]);
    if (!countryMap[countryName]) {
        countryMap[countryName] = [];
    }
    countryMap[countryName].push(year);
}

// 转换为目标格式
const result = Object.entries(countryMap).map(([name, yearList]) => {
    return {
        name,
        year: yearList.length === 1 ? yearList[0] : yearList
    };
});

console.log(result);

原代码问题说明

你之前的写法默认输入已经是国家为key、年份为值的结构化对象,但实际输入是扁平化的交替数组,缺少了成对解析和同国家年份聚合的步骤,因此输出不符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 13:24:04