Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

96
Vistas
JavaScript Calculate array of objects

I have some struggles calculating inside a for each function with JavaScript. I have one array of objects that looks like this:

[
    {
        "attribute_operator": "*",
        "attribute_value_price": 3
    },
    {
        "attribute_operator": "+",
        "attribute_value_price": 2
    },
    {
        "attribute_operator": "*",
        "attribute_value_price": 2
    }
]

As you see, every value has operator, and there is a starting price, so the real calculation should look like (if starting price is 6 for example):

6 * 3 + 2 * 2

So the output should be in that case 40.

I know how to do it for sum, but how to implement my operator easily?

tried like:

let total = starting_price.value

        calculate_objects.forEach((a: { attribute_value_price: number; }) => {
          total += a.attribute_value_price;
        });

        console.log(total);
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

This is a good case for reduce. The starting value is that starting_price, and each turn of the loop applies a little function related to the operand...

const starting_price = 6;
const operations = [{
    "attribute_operator": "*",
    "attribute_value_price": 3
  },
  {
    "attribute_operator": "+",
    "attribute_value_price": 2
  },
  {
    "attribute_operator": "*",
    "attribute_value_price": 2
  }
];

const operators = {
  '*': (a, b) => a * b,
  '+': (a, b) => a + b,
};

const result = operations.reduce((acc, el) => {
  let operator = operators[el.attribute_operator];
  let operand = el.attribute_value_price;
  return operator(acc, operand);
}, starting_price);

console.log(result);

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use string literal with eval function. eval function is useful when you want to calculate an expression.

const obj = [
    {
        "attribute_operator": "*",
        "attribute_value_price": 3
    },
    {
        "attribute_operator": "+",
        "attribute_value_price": 2
    },
    {
        "attribute_operator": "*",
        "attribute_value_price": 2
    }
]
let starting_price = 6;
let total = starting_price;

obj.forEach((a) => {
    total =eval(`${total}${a.attribute_operator}${a.attribute_value_price}`) ;
});

console.log(total);

Warning: Executing JavaScript from a string is an BIG security risk.

With eval(), malicious code can run inside your application without permission.

With eval(), third-party code can see the scope of your application, whitch can lead to possible attacks.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda