I'm only appending the final element to the JavaScript array

Currently, I have the following code: I'm endeavoring to create a new JSON object named dataJSON by utilizing properties from the GAJSON object. However, my issue arises when attempting to iterate over the GAJSOn object; only its last element is added to the array.

 var GAstring = '{"data":[{"bounceRate": "4","country":"Denmark"},{"bounceRate":
 "3","country":"Spain"},{"bounceRate":"6","country":"Romania"},
 {"bounceRate":"1","country":"Bulgaria"},{"bounceRate":"0","country":"Lithuania"},  
 {"bounceRate":"2","country":"Norway"}]}';
 var GAJSON = JSON.parse(GAstring);
 var viewJSON = {
    data:[]
 };
 var dataJSON = {};
 for(var i = 0; i < GAJSON.data.length; i++) {
     dataJSON["bounceRate"] = GAJSON.data[i].bounceRate;
     dataJSON["country"] = GAJSON.data[i].country;
 }
 viewJSON.data.push(dataJSON);

Answer №1

Make sure to include your push operation inside the loop for adding the new object.

 for(var j = 0; j < dataArr.length; j++) {
   updatedArr.push({
     item: dataArr[j].item,
     quantity: dataArr[j].quantity
   });
 }

See Example

Answer №2

Every time you're replacing values at

dataJSON["bounceRate"] = GAJSON.data[i].bounceRate;

Consider using this code instead:

var GAstring ='{"data":[{"bounceRate": "4","country":"Denmark"},{"bounceRate":"3","country":"Spain"},{"bounceRate":"6","country":"Romania"},     {"bounceRate":"1","country":"Bulgaria"},{"bounceRate":"0","country":"Lithuania"},     {"bounceRate":"2","country":"Norway"}]}';
 var GAJSON=JSON.parse(GAstring);
 var viewJSON = {
    data:[]
 };
 var dataJSON ={};
 for(var i =0; i<GAJSON.data.length; i++) {
     dataJSON[i] = [];
     dataJSON[i]["bounceRate"] = GAJSON.data[i].bounceRate;
     dataJSON[i]["country"] = GAJSON.data[i].country;
 }
 viewJSON.data.push(dataJSON);
console.log(viewJSON);

DEMO

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

How can I update the language of a button text in a React component?

Looking to update the button labels from a different language to English. Here is how it currently appears: ...

Purge POST request cache in Node.js

Currently, I have implemented nodemailer to enable users to contact me via email. Once the form data is submitted successfully, the page redirects to my homepage as intended. However, if an attempt is made to refresh the page, a confirmation alert pops up ...

Various input tools available for every Textarea

I'm grappling with this particular case. Each textarea should have its own toolbox, but currently only one is active (I anticipate having more than 2 areas, so JavaScript needs to be able to recognize them by ID) I attempted to use something like: f ...

Exploring logfile usage in JavaScript. What is the best way to structure the log?

Currently, I am developing a Python program that parses a file and records the changes made to it. However, I am facing a dilemma regarding the format in which this information should be saved for easy usage with JavaScript on the local machine. My objecti ...

Is there a way for me to determine which specific dependency is triggering a warning due to utilizing another dependency?

After analyzing my browser console, I found the following warnings: index.js:126 [WDS] Warnings while compiling. warnings @ index.js:126 (anonymous) @ socket.js:47 sock.onmessage @ SockJSClient.js:67 EventTarget.dispatchEvent @ sockjs.js:170 ...

In the virtual playground of Plaid's Sandbox, how can I replicate a fresh transaction and detect it using the Webhook feature?

Is there a way to trigger a simulated transaction within the webhook instead of just a DEFAULT_UPDATE event? I'm trying to find a way to simulate an actual transaction so that I can test my webhook integration. I've searched through the sandbox ...

Warning: The NextUI ThemeProvider may trigger a notice for additional attributes from the server, such as class and style

I recently integrated NextUI into my NextJS 14 application The issue seems to be originating from the ThemeProvider in my main providers.tsx file: 'use client'; import { NextUIProvider } from '@nextui-org/react'; import { ThemeProvide ...

Choose a random element from a string with Javascript

Could someone please help me figure out why my code isn't functioning as expected? I'm trying to randomly select three names from a list and ensure that no name is repeated. While I believe I am on the right track, something seems to be missing. ...

I am encountering an issue where the key is not located in the response array in PHP, causing my JavaScript chart to remain

Hey there! I'm currently working on a school project and could really use some assistance. The task at hand involves creating a web interface that can interact with an endpoint in order to: - Authenticate a registered user to retrieve an authenticati ...

I'm at a loss with this useState error, can't seem to figure

Could you please help me understand what is incorrect in this code snippet? import React, { useState } from 'react'; import UsrInput from '../component/UsrInput' import TodoItemList from '../component/TodoItemList' const ...

Having trouble getting my angular form validation to function properly

Even though I disabled Bootstrap's validation while using Angular, the validation for every input field still doesn't work. It seems like I have everything set up correctly. My code looks like this below with no success on input validation: < ...

Error in TypeScript when using Google Maps React with Next.js: there is a possibility that infoWindow.close is undefined

Working on a small project in next.js (typescript) utilizing the google maps api with a KmlLayer. I want my map to interact with another component, SensorInfo. The current setup allows for smooth interaction between them - when SensorInfo is closed, the in ...

Monitoring and recording user's browsing activities while excluding server-side scripting

Currently, I am working on creating a registration form which will direct users to a "Thank you" page once completed. However, I want to include a button on this confirmation page that will take users back to the previous page they were on before registeri ...

Identify duplicate values within an array and remove them based on certain conditions

Here is an example of a multidimensional array: $orders = array( array( 'id' => '123', 'name' => 'John', 'lastname'=>'Carter', 'rate' => '1.0' ...

The JavaScript function prints the variable using `console.log(var)`, however, it does not assign `var2` to

I've been following a tutorial on implementing push notifications in VueJS from this link. After running the register function on the created hook, I encountered an issue: register() { if ("serviceWorker" in navigator && "PushManager" in window ...

Nuxt - Sending Relative Path as Prop Leads to Error 404

I am currently working with an array of JSON objects that I need to import onto a webpage. The process involves iterating through the data and passing the objects as a prop to a component. One of the attributes within the JSON data is a relative path for a ...

What is the best way to extract a specific value from my JSON requests?

I need assistance in extracting a specific variable from the response after making a request. How can I access the data within my response? import requests import json url = "XXXXXX" payload = json.dumps({ "userName": "XXXXXX&q ...

Validating whether a condition aligns with any element within an array in JavaScript

Is there a better approach to determine if a condition matches any value in an array? For example, if I want to implement retry logic when receiving a 5xx error. var searchUserRequest = httpClient.request(searchUserRequestOptions, (res => { if(r ...

When choosing fields for JSON output, remember that string indices must be integers, not strings

I have been searching for answers for hours without any luck. Currently, I am using the following code to extract tweets from a list of tweets using the Twitter API: from twitter import Twitter, OAuth, TwitterHTTPError import os t = Twitter(auth=OAuth(OA ...

Prevent TypeScript from generalizing string literals as types

I have a constant Object called STUDY_TAGS with specific properties const STUDY_TAGS ={ InstanceAvailability: { tag: "00080056", type: "optional", vr: "string" }, ModalitiesinStudy: { tag: "00080061", type: " ...