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

What is the procedure for creating an array that contains elements taken sequentially from various arrays?

I am looking to extract specific elements from a given array: const initArray = [ { '18888': [ { unitId: 1, venueId: 18888, }, { unitId: 2, venueId: 18888, }, ], }, { &apos ...

Step-by-step guide on permanently updating the text of select options with JavaScript

Here is the code for a select option with different values: <select id="test" onchange="changeContent()"> <option>1</option> <option>2</option> <option>3</option> </select> The javascript function that chan ...

A guide on sending arrays from javascript to a Laravel controller through axios

Currently, I am utilizing Laravel 5.4 and Vue 2 to manage my data. I am facing an issue where I need to call a controller method using axios while passing two arrays. These arrays are crucial for making database requests in the controller and retrieving ne ...

Instructions for obtaining and assigning a reference to a recently cached associated object within the Apollo client InMemoryCache

My data consists of a set of interconnected items like this: book { id ... related_entity { id ... } } Once Apollo caches it, there are two separate cache objects. The related_entity field on book points to an EntityNode object. Everything ...

Having trouble retrieving information from a JSON object? Unable to retrieve property 'company_about' of an undefined object?

Here is the JSON data I have: [ { "id": 1, "job_id": 1, "company_profile": "Sales and Marketing", "company_about": "Established in 1992 , it is a renouned marketing company", "company_product": "Ford,Mustang,Beetle", "key_skills": ...

Toggle visibility of an Angular 4 component based on the current route

Hello there, I'm facing an issue and not sure if it's possible to resolve. Essentially, I am looking to display a component only when the route matches a certain condition, and hide another component when the route matches a different condition. ...

Struggling with a character entity in Javascript? Learn how to escape it and avoid any display issues (such as showing

document.title = ("welcome &rarr; farewell"); Trying to display the arrow symbol "→" but it's not showing correctly. Any tips on how to properly escape it? ...

How can I dynamically change a key in an object and replace it with a custom name while also updating its value?

Transform this =>>>>> {1: "Baroque", 2: "Glitch Pop ", 3: "Nu Jazz", 4: "Drumfunk", 5: "Bitpop", 6: "Latin Pop", 7: "Carnatic"} into this ==>>>> [{id: 1 name ...

Neglect to notify about the input text's value

Having trouble retrieving the text from a simple <input id="editfileFormTitleinput" type="text>. Despite my efforts, I am unable to alert the content within the input field. This is the code snippet I've attempted: $('#editfileFormTitleinp ...

Conflicting TypeScript enum types: numbers and numbers in NestJS/ExpressJS

Incorporating types into my NestJS server has been a priority. After creating a controller (a route for those who prefer Express), I attempted to define the type for params: public async getAllMessages( @Query('startDate', ValidateDate) start ...

Using Jquery for a Second Timer

I have a jQuery function that looks like the one below. The result is displayed in a span, but when the page is reloaded, this span briefly disappears and then reappears. Is there a way to prevent this from happening? I need it to stay visible at all tim ...

Utilize ES6 to import components for rendering on the server-side

In my ES6 React component file, I have a simplified version that utilizes the browser-specific library called store. Everything works perfectly fine on the browser: /app/components/HelloWorld.js: import React, { Component } from 'react'; import ...

Demystifying Iron Ajax: Unraveling the process of parsing an array of JSON objects from a successful

When making an AJAX call to the server, I receive a response in the form of an array of objects as JSON. [{"dms":[{"serialNo":"EG0022","status":"running","firmwareStatus":"ok","latitude":37.8688,"longitude":-144.2093,"toolType":1},{"serialNo":"EG0022","st ...

What are the steps to start using the Intersection Observer API right away?

Utilizing the Intersection Observer API, I can accurately determine whether an element is within the viewport or not. Is there a way to utilize the Intersection Observer API to detect if an element is in the viewport without relying on a callback function ...

Unable to refresh HTML table using Vuex data in Vue JS

I am new to working with Vue.js and particularly Nuxt. I am facing an issue with updating a table using data fetched from the backend. Even though I can see the data in the Vuex tab when the page loads, I cannot seem to populate the table with it. The func ...

Get the characters from a URL following a specific character until another specific character

Having some difficulty using JavaScript regex to extract a specific part of a URL while excluding characters that come after it. Here is my current progress: URL: With the code snippet url.match(/\/[^\/]+$/)[0], I am able to successfully extrac ...

PHP: Receiving notification if $_GET variable is void

When retrieving the array data, I use this code: $tags = $_GET['item']['tags']; if ($tags){ foreach ($tags as $tag){ The tags data is received from an input field, and it may be empty. If $tags does not receive any data, I enco ...

Using React to create an onScroll event listener within a mapped array

I am currently working on a setup where scrolling over an image mapped from an array updates the state with that image's coordinates, which in turn updates a Google Map. <CloudinaryContext cloudName="hcjmhcjf" fetchFormat="auto"> <div clas ...

Looking for assistance in showcasing information retrieved from an external API

I've been working with an API and managed to fetch some data successfully. However, I'm having trouble displaying the data properly in my project. Can anyone provide assistance? Below is a screenshot of the fetched data from the console along wit ...

"Exploring the parsing of a JSON stream in Scala Play using the ndjson

I'm faced with a challenge where I need to handle data from an endpoint that produces either application/stream+json or application/x-ndjson. The information about the latter format can be found at this URL. In my attempt to consume this endpoint usi ...