What is the best way to modify values within arrays of objects in JavaScript?

I need to update the values in an array of objects. The keys 1 and 2 are dynamic and pulled from a JSON file.

var rows = [
  {
    "1": "14",
    "2": "55",
    "named": "name1",
    "row": 7
  },
  {
    "1": "15",
    "2": "56",
    "named": "nameper",
    "row": 9
  },
  ...
]

The goal is to modify the data so that any name labeled "nameper" displays percentage values.

[
    {
      "1": "14",
      "2": "55",
      "named": "name1",
      "row": 7
    },
    {
      "1": "15%",
      "2": "56%",
      "named": "nameper",
      "row": 9
    },
    ...
  ]

Answer №1

items.forEach((individualItem) => {
   if(individualItem.type === "percentage"){
      individualItem["value1"] = individualItem["value1"] + "%";
      individualItem["value2"] = individualItem["value2"] + "%";
   }
})

Answer №2

You have the option to implement forEach, map, or a traditional for-loop.

Utilizing forEach.

rows.forEach((row) => {
    if (row["named"] === "nameper") {
        row["1"] = row["2"] + "%";
        row["2"] = row["2"] + "%";
    }
})

You can also achieve the same result using map!

Implementing for loop

for (var row of rows) {
    if (row["named"] === "nameper") {
        row["1"] = row["2"] + "%";
        row["2"] = row["2"] + "%";
    }
}

Answer №3

rows.forEach(row => {
    if (row["named"] === "nameper") {
        row["1"] = `${row["1"]} %`;
        row["2"] = `${row["2"]} %`;
    }
});

You are able to utilize a map function and verify the presence of "named" before making any necessary updates.

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

Developing a dynamic user interface using an Angular framework and populating it with

I am currently learning Angular (version 1) and facing an issue with my layout. I need to dynamically change the navigation based on the type of user that is logged in. To achieve this, I make an API request when the page loads to fetch the user object dat ...

Error message: The line chart in angular-chartjs is encountering an issue with the function t.merge not

I am currently working on implementing a line chart example from the following source: . However, I am encountering an error and would appreciate any guidance or pointers to resolve it. Here is the error displayed in the console. Below is the code snippe ...

Reactively created menu using JQuery

Looking to implement a dynamic JQuery menu using React (ES6). Utilizing the JQuery menu examples (https://jqueryui.com/menu/) as a guide, however, those examples only cover static menus. It doesn't clarify how to modify menu items like updating labels ...

Efficiently handling multiple JSON objects in a single PHP function

Currently, I am working on a project that involves populating two dropdown menus where the value of one depends on the other. Specifically, I have three dropdowns - one to select a class, and the other two for selecting subjects and exams based on the sele ...

Data loss from AngularJS multipartForm directive when redirecting to different routes

Having trouble with an Excel file uploader and data parsing in the routes? It seems like the FormData is getting lost when sent through the $http service route. Any advice or experience on how to handle this issue would be greatly appreciated! Html View: ...

After executing webpack, it has been noticed that one of the dist files consistently ends up empty

As someone who is new to webpack, I have successfully used the quick start guide to process a simple JS file from src to dist. Everything was working fine. However, I encountered an issue when trying to process more than one JS file. The original tutorial ...

What steps need to be taken to implement a structured autocomplete feature?

Let me break down the workflow for you: The user inputs something in a text field. Upon keypress, the frontend communicates with our backend script to retrieve and select a specific value. Once the value is selected, on leaving the input field, we query ...

Enhancing Website Functionality: How to Swap iFrame for DIV using PHP and AJAX

I am currently working on a website where I need to replace an iframe containing data stored in an invisible form with a div that updates its content using AJAX. If you don't want to read everything, skip to the end for my main question. The chall ...

Determine the Larger of Two Arrays and Save in a Separate Array

Hey There! I hope everyone is feeling great today. As for me, I've been tackling a code challenge that involves storing the greatest value. The basic idea is to compare arrays 1 and 2 to find the maximum number, and then store it in array 3. It sound ...

Steps for generating an array entry containing an ObjectId and a Number

I am a newbie when it comes to mongodb and I am attempting to create an entry like this: { "resources": [ { "amount": 1, "resource": { "_id": "61be82b9549b4ede ...

Incorporating HTML5 transitions into your website

After researching HTML5 transitions and adapting some examples, I finally achieved the desired effect. <!DOCTYPE html> <html> <head> <style> div { width: 50px; height: 50px; } div. ...

Is it possible to align an empty column to the right in bash scripting

I'm facing an issue with a script that prints columns, where the alignment gets messed up if the left column is empty. Currently, I'm iterating through an array, printing key/value pairs, and using the column command for formatting. Here's ...

Is your data coming in as NaN?

I am currently developing a basic webpage that has the capability to calculate your stake and determine your return, reminiscent of a traditional betting shop. As of now, I have successfully hard coded the odds into my page. However, while testing my code ...

Transferring information from server/app.js to Angular-fullstack controller with multer

I'm facing an issue transferring a filename from server/app.js to a controller in client/app/ Currently, I am utilizing Multer for handling file uploads, which is functioning correctly. However, I need to transfer the filename back to the client side ...

Reloading PHP code within a container

I have implemented a script that refreshes my messages.php within a div every 60 seconds using the following code: <script> jQuery().ready(function(){ setInterval("getResult()",60000); }); function getResult(){ jQuery.post("messages.php",function ...

What is the proper method for inserting a value at the start of an array?

I am trying to prepend a value of 0 to the beginning of an array. Here's a snippet of the code I have been working on: import numpy as np import matplotlib.pyplot as plt import math as m import loaddataa as ld import scipy.integrate as integrate ...

Troubleshoot: How to Fix the socket.io net::ERR_CONNECTION_TIMED_OUT

I am facing an issue with my website's real-time chat functionality. It works perfectly on localhost without any errors. However, when I try to run it on the server, I encounter the following error: http://my.domain:52398/socket.io/?EIO=3&transpo ...

Obtain the identifier of a div within nested HTML components by utilizing jQuery

How do I retrieve the id of the first div with the class: post, which is "367", using jquery in the given HTML code: <div id="own-posts"> <span class="title">Me</span> <div class="posts_container"> <div class="post"& ...

AngularJS - Swipe to update

I've been trying to use the pull to refresh plugin for Angular JS, but unfortunately it's not working for me. Even though I can see the text, when I try to pull nothing happens! I followed all the steps outlined on this GitHub page: https://githu ...

Inject a jQuery form submission using .html() into a div element

I am currently working on developing a basic forum where users can view listed topics and have the option to add new ones on-the-fly by clicking a link or image. How can I detect and handle the form submission event for the dynamically added form within an ...