Search code examples
javascriptobject-literal

How can i populate a complex literal object javascipt


I have 2 arrays( named countries and medals) with data that i need to put into one object literal in order to have the following output

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],
      },
    ],};

The years are randomly chosen.


Solution

  • Since you've created an output object

    1) You can directly copy all elements in output.categories array using spread syntax.

    2) For output.series you can use forEach to push an objects(equal to length of medals array length).

    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);