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

如何根据对象的count属性重复数组元素生成新数组?

实现按count重复name的数组

方法一:嵌套循环改造(最直观)

直接在原有循环基础上,针对每个对象的count值,重复将name推入结果数组:

function buildName(data) {
  const nameList = [];
  for (let i = 0; i < data.length; i++) {
    const { name, count } = data[i];
    for (let j = 0; j < count; j++) {
      nameList.push(name);
    }
  }
  return nameList;
}

方法二:数组方法链式调用(简洁现代)

用map为每个对象生成对应长度的重复name数组,再通过flat()扁平化合并:

function buildName(data) {
  return data.map(item => Array(item.count).fill(item.name)).flat();
}

方法三:reduce累加构建

通过reduce逐步将每个对象的重复name数组合并到结果中:

function buildName(data) {
  return data.reduce((result, item) => {
    return result.concat(Array(item.count).fill(item.name));
  }, []);
}

测试示例

调用函数并传入你的API数据:

const apiData = [
  { "name": "Rachel", "count": 4, "fon": "46-104104", "id": 2 },
  { "name": "Lindsay", "count": 2, "fon": "43-053201", "id": 3 },
  { "name": "Michael", "count": 5, "fon": "46-231223", "id": 4 }
];

console.log(buildName(apiData));
// 输出:["Rachel", "Rachel", "Rachel", "Rachel", "Lindsay", "Lindsay", "Michael", "Michael", "Michael", "Michael", "Michael"]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 19:09:28