What is the best way to sum two values in an array object and then replace the first value with the result?

I have an array containing two objects:

let xyz = [
  {amount: 1000, rate: 4},
  {amount: 100,  rate: 2},
  {amount: 700,  rate: 1}
];

The task is to multiply amount * rate and update the values in the amount key.

Desired output:

let result = [
  {amount: 4000, rate: 4},
  {amount: 200,  rate: 2},
  {amount: 700,  rate: 1}
];

Answer №1

To easily achieve this, you can utilize the .map() method:

let items = [{cost: 50, quantity: 2}, {cost: 20, quantity: 4},{cost: 30, quantity: 3}];

let totalCosts = items.map(item => ({...item, cost: item.cost * item.quantity}));

console.log(totalCosts);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Implementing Array.prototype.map():

   let dataList = [{amount: 1000, rate: 4}, {amount: 100, rate: 2}, {}, {amount: 700, rate: 1}]
   dataList.map(item => {
       if(!item.amount || !item.rate){  // Handling empty objects
           return item;
       }
       return {...item, amount: item.amount * item.rate}
   });

Answer №3

const data = [{amount: 1000, rate: 4}, {amount: 100, rate: 2},{amount: 700, rate: 1}]
let result = data.map(item => {
item.amount = item.amount * item.rate
return item
})
console.log(result)

Answer №4

In order to avoid creating a new Array, you can utilize the forEach method.

let xyz = [
  {value: 50, multiplier: 2},
  {value: 25, multiplier: 3},
  {value: 10, multiplier: 5}
];

xyz.forEach(entry => entry.value = entry.value * entry.multiplier)

console.log(xyz)

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

Having trouble with a FlatList component causing a blank screen in React Native?

I've been attempting to display data in a view using FlatList but instead of showing the predefined values, it's just showing a blank screen. This is what I have tried so far. Note: I purposely excluded import elements from react import { ...

NodeJs backend encounters undefined object due to FormData format request sent from Angular frontend

Never encountered this issue before despite having used this method for a long time. (Angular Frontend) const myFormData = new FormData(); myFormData.append("ok", "true"); this.http.put(my_Express_backend_url, myFormData); (Express ...

Using Object Values and Subvalues to Assign Element Attributes in jQuery

I have a weekly schedule that I update regularly using a static table layout: <table> <tr class="live gm fsp"> <td>Oct. 7</td> <td>12:30 pm</td> <td class="prog">Show 1</td> <td>Team ...

Is there a way in Jquery to retrieve the id of the clicked element and modify its name?

I am using a drag-and-drop website builder that utilizes HTML blocks, each with a unique ID. After dropping the blocks onto the canvas, I want to create a navigation menu that links to the IDs of each block. How can I retrieve the current ID of the block I ...

How to dynamically set Bootstrap navbar item as active based on current filename?

Currently, as I construct my website using the bootstrap framework, I am facing a minor challenge. I want to activate a menu item based on the filename by utilizing an if statement. For instance, when the filename is "about," the "about" tab should be act ...

Ensure consistency across browsers by disabling zoom functionality on touchpad inputs while still permitting scrolling actions

I am looking for a way to disable 2-finger zoom on trackpad "wheel" events while still allowing 2-finger scroll. On mobile, I have already disabled zoom with: <meta name="viewport" content="initial-scale=1, minimum-scale=1, m ...

Scroll a div using JavaScript/jQuery

I'm currently facing some challenges in resolving this issue. My goal is to pan a DIV using jQuery. The process is quite straightforward - on mouseDown, I capture X & Y coordinates and then subtract them from the newly obtained X & Y values during mou ...

Issue with Javascript redirect not working following form submission in combination with Asp Classic

After countless hours of research and experimentation, I find myself at a standstill. My web page is coded extensively, so I'll do my best to provide a concise summary. The core elements of my ASP CLASSIC page for creating tickets via a form are as f ...

Retrieving DOM Element in Angular from Freshly Loaded Template

Recently starting my journey with Angular, I have encountered a challenge when trying to access the DOM from a newly loaded template. Let me explain what's going on - index.html <div class="template" ng-app="myApp" ng-controller="myController"> ...

Can one function be invoked from another function in Node.js?

As I delve into learning Node.js through the process of converting an existing Rails project, I find myself grappling with callbacks and the asynchronous nature of Node. It has been a challenging journey to wrap my head around these concepts. Initially, m ...

How to include an array of data in an $http request using AngularJS

I am trying to store data in an array to the $http service in AngularJS. The way I am currently adding them to the service is as follows (and it is functioning correctly): var inputValueArray = new Array($scope.formdata); Currently, I am able to retriev ...

Comparing the cost of memory and performance between using classes and interfaces

As I delve into writing TypeScript for my Angular project, one burning question arises — should I use an Interface or a Class to create my domain objects? My quest is to uncover solid data regarding the actual implications of opting for the Class route. ...

Is there a way to transform a local array into remote JSON data?

I am attempting to retrieve an array from a remote server that is connected to a dynamic database. From what I have gathered on Ionic forums, it seems that I need to utilize the $http function from AngularJS. However, since I am new to AngularJS, the curr ...

Changing the color of a text box when it is disabled can be achieved through JavaScript

I'm facing an issue with the formatting of my HTML elements. Specifically, I have 2 combo boxes and one text box in which all 3 are disabled. However, when they are disabled, the background color of the text box does not match that of the combo boxes. ...

Looping Feature in Ionic Framework's Slides Component

Currently, I am working on developing an application using Ionic-Angular. When it comes to incorporating slides in my app, I opted for the ionic 4 ion-slides component. Everything was going smoothly until I wanted to enable looping for the slides so that u ...

Difficulty arises when transferring files in Node.js from one directory to another

Attempting to use node.js to transfer files from the currentFolder(root of project)/node_modules/mime/ to currentFolder(root of project)/files/, encountering an error: events.js:85 throw er; // Unhandled 'error' event ^ Error: ...

Real-time changes may not be instantly reflected in the model update

I need to add two numbers together and display the sum in a third input field: HTML <div ng-app="myApp"> <div ng-controller="MainCtrl as mainCtrl"> Main {{mainCtrl.foo}} <br/> <input type="text" ng-model="mainCtrl.foo"/> ...

SquirrelFish appears to be lacking "bind()", so how can one attach a JS callback to "this" in its absence?

Does anyone know a way to attach a JS callback to "this" without using "bind()"? Based on Samsung specifications: In 2013 with V8: everything functions as expected (refer to linked screenshot, too large to include here) In 2012 with SquirrelFish: encoun ...

Transform Vue military time to regular time format

I am retrieving the arrivalTime from todos.items. As I fetch the arrivalTime, it is sorted using the sortedArray function(), which converts the times to military time. Is there a way to change the sorted military time values to standard time format after s ...

How can you access the preloaded resolve value in AngularJS ui-router when the $stateChangeSuccess event is triggered?

$stateProvider.state('home', { url: '/', resolve: { person: function() { return 'good' } } Can you help me figure out how to access the value of 'person' in the $stateChangeSuccess callback f ...