Search code examples
javascriptarraysjavascript-objectsclone

Multiply/Clone multiple times objects inside and array in JavaScript


Having an array of objects in this format:

const data = [
{country_id: 1, country: "Greece", value: 3},
{country_id: 2, country: "Cyprus", value: 2},
{country_id: 3, country: "Turkey", value: 4}
]

how can I multiply/clone each of the objects to get the following array of objects using JavaScript? I want to multiply each object as many times as specified in value and get a new array.

const new_data = [
{id: 1, country_id: 1, country: "Greece", value: 3},
{id: 2, country_id: 1, country: "Greece", value: 3},
{id: 3, country_id: 1, country: "Greece", value: 3},
{id: 4, country_id: 2, country: "Cyprus", value: 2},
{id: 5, country_id: 2, country: "Cyprus", value: 2},
{id: 6, country_id: 3, country: "Turkey", value: 4},
{id: 7, country_id: 3, country: "Turkey", value: 4},
{id: 8, country_id: 3, country: "Turkey", value: 4},
{id: 9, country_id: 3, country: "Turkey", value: 4}
]

My best attempt so far is this one using Object.assign but unfortunately the map returns the same array as in data:

const new_data = data.map((d, i) => {
    for (var i = 0; i < d.mult; ++i) {
      Object.assign({}, d[i]);
    }
    return d;
 })

Solution

  • You could do it like this, where you simply fill an array with value elements, and map it to a clone of the original element:

    const data = [
    {country_id: 1, country: "Greece", value: 3},
    {country_id: 2, country: "Cyprus", value: 2},
    {country_id: 3, country: "Turkey", value: 4}
    ]
    
    console.log(
        data.flatMap((el) => new Array(el.value).fill(null).map(e => ({...el}))))