Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

123
Visualizações
Create objects with logic using passed in arguments in function

I have this function where I create an object const dataObj to be used in the function, with the labels and valuesX passed in.

function drawChart(labels, values0, values1, values2, ...many more objects) {
    const dataObj = {
        labels: labels,
        datasets: [
            {
                fill: false,
                label: "temp0",
                backgroundColor: 'red',
                borderColor: 'red',
                data: values0
            },
            {
                fill: false,
                label: "temp1",
                backgroundColor: 'purple',
                borderColor: 'purple',
                data: values1
            },
            {
                fill: false,
                label: "temp2",
                backgroundColor: 'yellow',
                borderColor: 'yellow',
                data: values2
            },
            ...many more objects
        }
    }
    ...not meaningful code
}

Is there a way to create the dataObj with logic inside the function instead of creating all the objects literally one by one with a for loop or similar? My problem comes when I need to refer to the respective arguments valueX in the logic to create the objets with logic.

My approach is to create a functions that generate the objects, but my problem comes when I need to refer to the argument with logic. Check the comment //PROBLEM HERE

function getDatasetArray(values0, values1, values2, values3, values4,
    values5, values6, values7, values8, values9, 
    values10, values11) {
    const datasets = [];
    const colors = [];
    const lables = [];

    for(let i = 0; i < 12; i++) {
        const obj = {
            fill: false,
            label: lables[i],
            backgroundColor: colors[i],
            borderColor: colors[i],
            data: values0 // PROBLEM HERE
        }
        datasets.push(obj);
    }

    return datasets;
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

you can update your getDatasetArray as

const getDatasetArray = (...values) => { // take values using es6-spread
  const datasets = [];
  const colors = [];
  const lables = [];

  for (let i = 0; i < values.length; i++) { // iterate for values
    const obj = {
      fill: false,
      label: lables[i],
      backgroundColor: colors[i],
      borderColor: colors[i],
      data: values[i]  // put value into data-key
    }
    datasets.push(obj);
  }
  return datasets;
}

and drawChart as

function drawChart(labels, ...values) { //use spread here too
  // rest of your code
}
about 4 years ago · Juan Pablo Isaza Relatório

0

take in your values as an array.

function drawChart(labels, values) { // take values as array
    const dataObj = {
        labels: labels,
        datasets: []
    }
    let colors = ["red", "purple", ...], i = 0;
    values.forEach(value => {
        let obj = {
                fill: false,
                label: "temp" + i,
                backgroundColor: color[i],
                borderColor: color[i],
                data: values[i]
        } 
        dataObj.datasets.push(obj);
        i++;
    });
    // ...
}
about 4 years ago · Juan Pablo Isaza Relatório

0

You need to pass values as an array as arguements cannot be consumed with indices.

Solution

function drawChart(values) {
  // rest of code

  for(let i = 0; i < 12; i++) {
    const obj = {
      // ..
      data: values[i] // access i-th value here
    }

    datasets.push(obj);
  }

  // rest of code
}

Note

It's a bad practice to pass so many arguments to your function as it would result in poor code quality which is difficult to maintain. Moreover, the type of data each argument represents is same, i.e. value so it must be grouped in an object or here, array.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda