How can I substitute a specific portion of a string with values that correspond to items in an object array?

I am currently working on a task that involves extracting values from objects in a string to perform mathematical operations. While I have managed to retrieve the data and match the values enclosed in brackets, I am facing a roadblock in terms of what steps to take next or whether there might be a more efficient approach to accomplish this. Here is a sample of the scenario I am dealing with:

var array = [{name: M, value: 45},{name: F, value: 23},{name: L, value: 9}]
var string = '( 2 * [M] ) * ( 5 / [F] ) * ( 100 + [L] )'

In essence, I am seeking a solution where I can substitute the value of "M" for "[M]", the value of "F" for "[F]", and so forth within the string formula.

Answer №1

If you're looking to work with formulas and calculations, give nerdamer a try. It's a great tool for handling mathematical expressions.

let variables = {M: 45, F: 23, L: 9};
let equation = '( 2 * M ) * ( 5 / F ) * ( 100 + L )';

console.log(
  equation,
  '=',
  nerdamer(
    equation,
    variables
  )
  .evaluate()
  .text()
);
<script src="https://cdn.jsdelivr.net/npm/nerdamer@latest/nerdamer.core.js"></script>

For a simpler approach, you can use the following method:

let variables = {M: 45, F: 23, L: 9};
let equation = '( 2 * [M] ) * ( 5 / [F] ) * ( 100 + [L] )';

function calculate(equation, variables)
{
  let newEquation = equation.replaceAll(/\[[A-Z]\]/gi, function(v)
  {
    return variables[v[1]];
  });
  
  return eval(newEquation);
}

console.log(calculate(equation, variables));

Answer №2

Check out this neat one-line solution:

const arr = [{name: 'M', value: 45},{name: 'F', value: 23},{name: 'L', value: 9}]
const str = "( 2 * [M] ) * ( 5 / [F] ) * ( 100 + [L] )";

const doCalculation = (arr) => arr.reduce((acc, val)=>{ return acc.replace(`[${val.name}]`, val.value)}, str);

console.log('Final Result: ', eval(doCalculation(arr)));

Answer №3

Here is a helpful code snippet for you to explore. Enjoy!

let values = [{item: "X", quantity: 30}, {item: "Y", quantity: 12}, {item: "Z", quantity: 5}];
let formula = '( 3 * [X] ) * ( 10 / [Y] ) * ( 50 + [Z] )';

const calculateValue = (array, equationWithVars) => {
  let result = equationWithVars;
  
  array.forEach(element => {
    result = result.replaceAll(`[${element.item}]`, element.quantity);
  })
  
  return result;
}

console.log(calculateValue(values, formula));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Calculating the number of duplicate lines in a file with node.js

I am currently working on a project where I need to read a large .csv file line by line, extract the first column (which contains country names), and then count the number of duplicates for each country. For example, if the file contains: USA UK USA The ...

Using Next.js with Firebase emulators

I've been struggling to configure Firebase's V9 emulators with Next.js, but I keep running into the same error message. See it here: https://i.stack.imgur.com/Uhq0A.png The current version of Firebase I'm using is 9.1.1. This is how my Fir ...

Ways to prompt a window resize event using pure javascript

I am attempting to simulate a resize event using vanilla JavaScript for testing purposes, but it seems that modern browsers prevent the triggering of the event with window.resizeTo() and window.resizeBy(). I also tried using jQuery $(window).trigger(' ...

IE does not render the output of multiple AJAX requests

Desiring an autocomplete feature for an input box that displays results in a div below it, I wrote this shortened code. It functions flawlessly on Chrome and Firefox - when searching for "Eggs" and then "Milk", their respective results appear. However, Int ...

rearranging nodes from multiple arrays into a single array and then repositioning them within the parent array using angularjs

[![enter image description here][1]][1]I am working with AngularJS and I have multiple arrays named list1, list2, and list3. Each array is used in a different list. Within my application, there are two buttons and two divs - the left div displays elements ...

Appending an item to an array in TypeScript

I'm feeling lost. I'm attempting to insert new objects into an array in TypeScript, but I encountered an error. My interface includes a function, and I'm puzzled. Can anyone offer guidance? interface Videos{ title: string; descriptio ...

Timepicker Bootstrapping

I've been searching for a time picker widget that works well with Bootstrap styling. The jdewit widget has a great style, but unfortunately it comes with a lot of bugs. I'm on a tight deadline for my project and don't have the time to deal w ...

Display URL in NodeJS Express without the need for the .html extension

I am currently utilizing Express 4.12.3 to serve static files for a website. My goal is to navigate to example.com/mypage and have it retrieve /mypage.html. Essentially, I want to access the page without needing to include the .html extension in the URL. ...

The Node.js server is outputting an HTTP status code of 404

I have recently set up a small server. Interestingly, when I attempt to perform a GET request to my server through a browser, I can see the correct data. However, when I try to make a POST request to my server using code, I receive an HTTP status 404 error ...

Black-colored backdrop for Mui modal

Currently working with a mui modal and encountering an issue where the backdrop appears as solid black, despite setting it to be transparent. I attempted to adjust the color to transparent, but the issue persists. ...

Utilizing the Power of AJAX in Combination with an Event Loop

I have a function that is supposed to make AJAX requests with an event loop while taking 9 inputs at the top and querying them from a database. Currently, it only logs to the console but will eventually perform more actions. However, I am encountering an ...

Disable the ability to close the dialog box by clicking

this is my dialog <div *ngIf="visible" class="overlay" (click)="close()"> <div role="dialog" class="overlay-content"> <div class="modal-dialog" (click)="$event.stopPropagation()"> <!-- Modal content--> ...

Is it possible to view the object sent from AJAX to PHP in PHP using a debugger?

I'm facing an issue where I am making an AJAX call to a PHP file, sending a JSON object as a parameter from JavaScript. The PHP file is supposed to perform some logic with the object and return it using json_encode('whatever');. However, the ...

When a form input is submitted, the webpage will refresh with a new

I have a form embedded on my WordPress page. I want to identify users without referrers so that I can set the referrer for them automatically (the referrer part is handled by a plugin). The registration form URL looks like this: The code provided below w ...

Retrieve the package.json file for a specific package by making an HTTP request to public repositories

I’ve been searching online but haven’t found a satisfying answer to my question yet. My main objective is to generate a dependency tree for a particular npmjs library of a specific version, like retrieving the dependency tree for the angular library v ...

Problem with ng-repeat not updating select dropdown options

Struggling with AngularJS while working on a project, I encountered an issue with a 'select-options' element. Currently, I am making a $http request to retrieve data from a Cloud SQL database. To achieve this, I am invoking a function from my f ...

What causes Firefox's CPU to spike to 100% when a slideshow begins that adjusts the width and left coordinates of certain divs?

Seeking Advice I'm in need of some help with identifying whether the code I'm working on is causing high CPU usage in Firefox or if it's a bug inherent to the browser itself. The situation is getting frustrating, and I've run out of so ...

Tips on how to direct the attention to a text box within a unique dialog, ensuring that the blinking cursor highlights the input area

Is there a way to set autofocus on a textbox when opening a custom dialog box? I've tried using the autofocus attribute for the input field, but it doesn't seem to work for me. Can anyone provide guidance on how to achieve autofocus for a textfie ...

What is preventing me from accessing a function that is declared using function declaration while using a debugger?

When pausing at the debugger statement, an attempt to call foo results in a ReferenceError. It appears that the function is not defined within the script's context or scope, similar to how a local variable like x is. The script example.js is as follo ...

Tips for navigating libraries with Google CAJA

Is there a way to configure Google Caja to allow specific libraries to work without being sanitized? I have my own CAJA server and an application based on NodeJS. I'm providing users with code that is mostly related to charts and graphs, but certain ...