Iterate over a JSON array and update each object with JavaScript

If I have the subsequent JSON array (here are the initial 3 in a set of 100)

var information = [
                {
                    "percent_change_1h": "2.19",
                    "percent_change_24h": "-1.07",
                    "percent_change_7d": "-7.2",
                },
                {
                    "percent_change_1h": "1.96",
                    "percent_change_24h": "-2.13",
                    "percent_change_7d": "-11.64",
                },
                {
                    "percent_change_1h": "9.21",
                    "percent_change_24h": "18.31",
                    "percent_change_7d": "18.3",
                }
            ]

How do I navigate through this data, and insert an object into each dataset so that afterward it resembles:

var information = [
                {
                    "percent_change_1h": "2.19",
                    "percent_change_24h": "-1.07",
                    "percent_change_7d": "-7.2",
                    "new_key": "newvalue"
                },
                {
                    "percent_change_1h": "1.96",
                    "percent_change_24h": "-2.13",
                    "percent_change_7d": "-11.64",
                    "new_key": "newvalue"
                },
                {
                    "percent_change_1h": "9.21",
                    "percent_change_24h": "18.31",
                    "percent_change_7d": "18.3",
                    "new_key": "newvalue"
                }
            ]

I have experimented with a for key in information loop as well as a forEach method but have not been successful.

Answer №1

One way to accomplish this is by using a basic loop structure. You can utilize the convenient for..of syntax for this task:

for (const item of list) item.updated_key = "updatedvalue";

Answer №2

One approach is to iterate through the object and add a new value using the following function:

var info = [
                {
                    "percent_change_1h": "3.45",
                    "percent_change_24h": "-0.98",
                    "percent_change_7d": "-9.8",
                },
                {
                    "percent_change_1h": "0.75",
                    "percent_change_24h": "-1.32",
                    "percent_change_7d": "-6.45",
                },
                {
                    "percent_change_1h": "5.67",
                    "percent_change_24h": "12.34",
                    "percent_change_7d": "26.79",
                }
            ]

function insertValue(info, newVal)
{
  for(var index = 0; index < info.length ; index++)
  {
    info[index]['newVal'] = newVal;
   }
   return info;
}

console.log(insertValue(info,'newVal'));
.as-console-wrapper {
    bottom: auto;
    max-height: 100%;
    top: 0;
}

Answer №3

Implement map() method:

elements = elements.map(elem => ({...elem, new_property: "newproperty"}));

var elements = [
  {"value1": "123",},
  {"value2": "456",}
];

elements = elements.map(elem => ({...elem, new_property: "newproperty"}));

console.log(elements);

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

Generating a hyperlink with specific attributes

Hey everyone, I'm currently working on creating a link tag using JavaScript. I want to add parameters to the link so that when a user clicks on the button, it redirects to a specific URL with those parameters attached. Here's an example of what I ...

express middleware is not compatible with prototype functions

I've encountered a perplexing issue while working with the node.js express framework. Let's say I have a file called test.js containing the following code: function a(){ } a.prototype.b = function(){ this.c("asdsad"); } a.prototype.c = f ...

What is the best way to limit the length of text in a div if it surpasses a

As I work on a website, users have the ability to add headings to different sections of a page. For example: M11-001 - loss of container and goods from Manchester Some headings can be quite detailed, but in reality, only the first few words are needed to ...

Encountering issues in parsing JSON for PhoneGap Application

I've been struggling with parsing JSON data for a unique PhoneGap application that is dynamically generated by a localStorage variable. The PHP script is functioning properly, but the JavaScript code seems to be encountering issues when trying to pars ...

Executing an angular directive within the template of another javascript framework

I am currently in the process of converting an angular application to ember.js as a way to expand my skill set. Within our project, we have a custom angular module that was created through a directive. Due to the time it will take to port that component o ...

For each item they possess, attach a "!" at the end

Given an array, I am trying to use map to add an exclamation mark to each item in the array. For example: Before - items: ["ball", "book", "pen"] After - items: ["ball!","book!","pen!"] const array = [ { username: "john", team: "red", score: 5 ...

Mask the input numbers to a specific format

I have a custom input component that I use to manage user inputs. export const MyCustomInput = (props) => { const { name, required, value, label, onChange, type, icon, } = props const Icon = () => (icon ? <div cl ...

What could be preventing the fill color of my SVG from changing when I hover over it?

I am currently utilizing VueJS to design an interactive map showcasing Japan. The SVG I am using is sourced from Wikipedia. My template structure is illustrated below (The crucial classes here are the prefecture and region classes): <div> <svg ...

Is it possible to make changes to local storage data without impacting the rest of the data set?

https://i.sstatic.net/BBcJF.pngI am looking for a way to modify specific data in the local storage without affecting any other stored information. However, I have encountered an issue where editing values works correctly for the first three attempts, but ...

Is it possible to execute a task following the closure of an element in HTML?

I'm looking to trigger a different JavaScript method after closing a dropdown list. Any ideas on how I can achieve this? UPDATE: Here's the dropdown list in question: https://i.sstatic.net/QYq4U.png. Whenever I click on an element within the li ...

Discover the flawless way to transmit client geolocation to a server. Encounter an intriguing hurdle: Unable to access undefined properties (specifically 'loc') while reading

I encountered an error that says "TypeError: Cannot read properties of undefined (reading 'loc')". This error was triggered when I attempted to pass the user's location to a server through a POST request. In my HTML file, I have included th ...

I am looking to showcase the data retrieved from an API by arranging it into columns with automatic data filling in a project using React.js and MySQL

When using the onKeyUp event to trigger an API call without submitting the form, I successfully fetched data in response if the mobile number matched. However, I am struggling to understand how to display this data as a default value in columns. I have tri ...

Watch the video and follow along with your mouse using jQuery

Wouldn't it be cool to have a video play and follow your mouse pointer when you hover over the red box? And then once you move away, the video stops and disappears. Check out my progress so far: jsfiddle Here's the jQuery code I've used: $ ...

Merging JSON array with a different dataset

I have data in an array format like [1,2,3] and I am trying to join it with another table. This is the query I am using: select RCM.header_details->'auditAssertion' as auditassertion from masters."RCM" RCM left join reference."AUDIT_A ...

Unable to activate IndexedDb persistence with Firebase v9 in a Next.js PWA

I'm having trouble enabling IndexedDb persistence in Firebase v9 for a Next.js PWA. These errors keep popping up: index.js // main Firebase file import { initializeApp } from 'firebase/app' import { getAuth } from 'firebase/auth' ...

Changing multi-dimensional arrays in Python

I have a process where I retrieve items from a database and add them to an array, but I need them to be formatted a certain way: tmpArray = [0] sql = "SELECT value FROM employees;" c.execute(sql) rows = c.fetchall() for row in rows: tmpArray. ...

Regular expression for textarea validation

I'm currently working on creating a regex for a textarea in my Angular 8 application. The goal is to allow all characters but not permit an empty character at the start. I've experimented with 3 different regex patterns, each presenting its own s ...

Received null as parameter in the JSON data

Currently, I am working on developing an app using REST to enhance my skills in the domain. While I have experience working with JSP and servlets in the past, I have now recognized that using JSON in a REST API is the new trend. So, I decided to give it a ...

The magnifying glass icon is missing from the autocomplete search feature

After creating an autocomplete search functionality that queries my mysql database, I encountered a slight issue. Here is the code snippet showcasing my implementation: <div class="search-bar"> <div class="ui-widget"> <input id="ski ...

How can the issue of v-slot missing in Vue2.7 be resolved?

After executing the given code, the results displayed are captured in Google Chrome. Below is a snippet of the code used: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-e ...