我如何填充复杂的文字对象javascript

How can i populate a complex literal object javascipt

我有 2 个数组(命名国家和奖牌),其中包含我需要放入一个对象文字中的数据,以便获得以下输出

let countries= ['Korea', 'United States', 'Germany', 'Canada', 'Austria'];

let medals = ['Gold medal', 'Silver medal', 'Bronze medal'];

let output = {
     categories: [],
     series: [
      {
        medal: '',
        year: [],
      }
    ]
 };

for(let i = 0; i < countries.length; i++){

   for(let j= 0; j < medals.length; j++){
   
      output.categories.push(countries[i]);
      output.series[j].medal = medals[j];
      output.series[j].year.push('1993');//any random year
   }
}

//desired output
    output = {
    categories: ['Korea', 'United States', 'Germany', 'Canada', 'Austria'],
    series: [
      {
        medal: 'Gold medal',
        year: [1993, 1996, 2014, 2017, 1999], //1993 for Korea, 1996 for USA,..
      },
      {
        medal: 'Silver medal',
        year: [1990, 1996, 2012, 2017, 1993],
      },
      {
        medal: 'Bronze medal',
        year: [1987, 1992, 2014, 2013, 2003],
      },
    ],};

年份随机选择。

因为您已经创建了一个 output 对象

1) 您可以使用 spread syntax.

直接复制 output.categories 数组中的所有元素

2) 对于 output.series 你可以使用 forEach 推一个物体(等于奖牌数组的长度)。

medals.forEach((s) => {
  output.series.push({
    medal: s,

    // Second approach using Array.from
    year: Array.from({ length: countries.length }, () =>
      randomNumber(1900, 2021)
    ),
  });
});

let countries = ["Korea", "United States", "Germany", "Canada", "Austria"];

let medals = ["Gold medal", "Silver medal", "Bronze medal"];

let output = {
  categories: [],
  series: [],
};

output.categories = [...countries];

function randomNumber(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}

medals.forEach((s) => {
  output.series.push({
    medal: s,
    year: Array(countries.length)
      .fill(0)
      .map(() => randomNumber(1900, 2021)),
  });
});

console.log(output);

let countries= ['Korea', 'United States', 'Germany', 'Canada', 'Austria'];
let medals = ['Gold medal', 'Silver medal', 'Bronze medal'];
let output = {
    categories: countries,
    series: medals.map(medal => ({
        medal,
        year: [ 1993 ]
    }))
};
console.log(output);