Calculating the sum of values in a specific position within an array of Javascript

Here is an array that needs to be updated:

let arr = [ { "Id": 0, "Name": "Product 1", "Price": 10 }, 
            { "Id": 0, "Name": "Product 1", "Price": 15 } ]

I am looking for a way to add 1 to all the Price values, resulting in:

let Final_arr = [ { "Id": 0, "Name": "Product 1", "Price": 11 }, 
                  { "Id": 0, "Name": "Product 1", "Price": 16 } ]

Any suggestions on how to achieve this? Thanks! ;)

Answer №1

Iterate over the array and increase the value of price: Remember that this action will change the original array, use arr.slice(0).forEach( ... to maintain the original array.

let arr = [{
    "Id": 0,
    "Name": "Product 1",
    "Price": 10
  },
  {
    "Id": 0,
    "Name": "Product 1",
    "Price": 15
  }
]

arr.forEach((e) => {
  return e.Price++
});

/* 

const newArr = arr.slice(0).forEach((e) => {
  return e.Price++
});


*/
console.log(arr)

Answer №2

Another option is to utilize a for loop:

var items = [{
    "Id": 0,
    "Name": "Product 1",
    "Price": 10
  },
  {
    "Id": 0,
    "Name": "Product 1",
    "Price": 15
  }
];

for (var index = 0; index < items.length; index++)
  items[index].Price++;

console.log(items);

Answer №3

arr.forEach((elem) => { elem.Price = elem.Price + 1 });

Answer №4

To create a new array with updated values, you can duplicate the existing array and apply mapping as shown below:

let originalArray = [ { "Id": 0, "Name": "Product 1", "Price": 10 }, 
                      { "Id": 0, "Name": "Product 1", "Price": 15 } ];
            
let newArray = JSON.parse(JSON.stringify(originalArray)).map(function(item){
  item.Price++;
  return item;
});

console.log(newArray);

Answer №5

To achieve this using ES2015 syntax, you can utilize the following code:

const New_arr = arr.map((element) => {
    return { ...element, price: element.Price + 1 };
});

If you prefer using vanilla JavaScript instead, the code would look like this:

var New_arr = arr.map(function (element) {
    return { Id: element.Id, Name: element.Name, Price: element.Price + 1 };
});

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

Warning in Next.js: Each element in a list requires a distinct "key" property

Currently, I am in the process of building an e-commerce platform using Nextjs. My current focus is on enhancing the functionality of the myCart page, which serves as a dashboard for displaying the list of items that have been ordered. Below is the code s ...

Error: When executing the npm run build command, I encountered a TypeError stating that Ajv is not a

I keep encountering an issue whenever I try to execute npm run build error: /node_modules/mini-css-extract-plugin/node_modules/schema-utils/dist/validate.js:66 const ajv = new Ajv({ ^ TypeError: Ajv is not a constructor at Object.<anon ...

Adding a unique key to every element within a JavaScript array

I am working with the array provided below which contains simple values. My goal is to add a key id before each value in the array, resulting in something like this: ["id:a", "id:b","id:c","id:d"]. Is there an easy way to achieve this? Any assistance would ...

Various successful functions in Ajax

I am currently using an Ajax script to fetch data from my database and insert it into multiple textboxes. Along with posting the data, I also need to perform calculations using these textboxes. However, upon running the script, I noticed that all calculat ...

Combining Extjs combo with autocomplete functionality for a search box, enhancing synchronization capabilities

When using autocomplete search, I've encountered an issue. If I type something and then make a mistake by deleting the last character, two requests are sent out. Sometimes, the results of the second request come back first, populating the store with t ...

Avoiding unlimited re-renders when using useEffect() in React - Tips and Strategies

As a new developer, I recently built a chat application using socket io. In my code, I have the useEffect hook set to only change when the socket changes. However, I also have setMessage within the body of useEffect(), with socket as a dependency. Unfortun ...

Experiencing excessive CPU usage while utilizing a progress bar in Angular

Whenever I try to load a page with 2 progress bars, my CPU usage goes through the roof... I decided to investigate and found that once I removed them, the site's speed improved significantly. Here's a code snippet of one of the progress bars: ...

Direct a flow to an unknown destination

What I am trying to achieve is writing a stream of data to nowhere without interrupting it. The following code snippet writes the data to a file, which maintains the connection while the stream is active. request .get(href) .on('response', func ...

I am currently implementing a unique scrollbar component to enhance the user experience within my list of options displayed in the MUI Autocomplete feature

Seeking a way to integrate a custom scroll feature from this npm package into the list of options for Material UI autocomplete. Consistency is key in my application, and the default scroll appearance on mui autocomplete doesn't quite align with the re ...

Sometimes the AngularJS scope is refreshed only intermittently

I am encountering an issue with a list of cards retrieved from an API and displayed in a table using ng-repeat. The problem arises when I attempt to delete a card - sometimes it remains in the view, while other times it disappears as expected after confirm ...

What is the best way to display compiled Transcluded HTML in Angular?

I am facing a challenge in trying to display customized HTML content using Angular directives for nesting divs multiple times. When I execute the code below, the transcluded tag is displayed correctly but the browser output shows the string text " ". I att ...

Having trouble closing my toggle and experiencing issues with the transition not functioning properly

Within my Next.js project, I have successfully implemented a custom hook and component. The functionality works smoothly as each section opens independently without interfering with others, which is great. However, there are two issues that I am facing. Fi ...

Error: Child component received an undefined prop

Within my parent component, I have three child components. The first child component is a form that, upon submission, passes data to the second and third child components through props via the parent component. However, in one of the child components, the ...

Exporting Canvas data without the alpha channel

I am looking for a way to resize images that are uploaded in the browser. Currently, I am utilizing canvas to draw the image and then resize it using the result from the toDataURL method. A simplified version of the code (without the upload section) looks ...

HTML link with "mailto:" not opening in a new tab

Just posted for the first time! I'm attempting to create a mailto link using 'templated' JavaScript that pulls specific data from a JSON object: var menu = { "menu": [ { "title": "let's talk", "link": "mailto:<a href ...

When I click on the md-select element, a superfluous "overflow-y: scroll;" gets added to the <body> of my webpage

Typically, I have the following styles on my body: element.style { -webkit-app-region: drag; } However, when I interact with a md-select element (you can observe this behavior on the provided link), additional styles are applied. element.style { -w ...

Exploring the limitations of middlewares in supporting independent routers

When I examine the code provided, it consists of three distinct routers: const Express = require("express") const app = Express() // Three independent routers defined below const usersRouter = Express.Router() const productsRouter = Express.Router() cons ...

What is causing ES6 Class properties to be concealed by Higher Order Functions?

UPDATE: Added new screenshots to provide clarity at the end. My current challenge involves utilizing high order functions to combine subclasses/mixins. I've noticed that I can only access properties from the first class I extend, and only properties ...

Tips for developing screen reader-friendly AJAX areas and managing updates to the DOM?

My interactive user process operates in the following manner: Users encounter a dropdown menu featuring a selection of cities. Upon picking a city, an AJAX request retrieves all buildings within that city and inserts them into a designated div (the AJAX ...

Automatically scroll the page upon loading if the user is at the top of the page

Is there a way to trigger an action only when the page is detected to be at the very top, without executing it otherwise? I think maybe using an if statement could work, but I'm not entirely sure how to go about it. For instance, I'd like the pa ...