To add an object to an array in Javascript, use the following format: [{...}, {...}]

Let's say we have a variable named var testVar = []; and we receive data via ajax in the following format:

{
  "Country": "ALA Aland Islands",
  "CountryCode": "AX",
  "Slug": "ala-aland-islands",
  "Population": 100000,
  "Teenagers": 50000,
  "Mid": 20000,
  "Seniors": 30000
},
{
  "Country": "Afghanistan",
  "CountryCode": "AFR",
  "Slug": "afghanistan",
  "Population": 200000,
  "Teenagers": 50000,
  "Mid": 100000,
  "Seniors": 50000
}

We attempt to loop through this data and store the population per country in the array (testVar) using the following approach:

function obj(key, val) {
this.key = key;
this.val = val;
}
for(i=0;i<data.lenght;i++){
    var x = new obj("y",data[i].Population);
    testVar.push(x); 
}

Although the above code snippet functions as intended, it does not generate the desired output. Our objective is for the data structure to look like this instead:

[{...}], [{...}] rather than [obj,obj]

Answer №1

It's actually quite a straightforward fix

The only action required is to map the data received from the AJAX call to extract just the population information.

let data = [{
    "Country": "ALA Aland Islands",
    "CountryCode": "AX",
    "Slug": "ala-aland-islands",
    "Population": 100000,
    "Teenagers": 50000,
    "Mid": 20000,
    "Seniors": 30000
  },
  {
    "Country": "Afghanistan",
    "CountryCode": "AFR",
    "Slug": "afghanistan",
    "Population": 200000,
    "Teenagers": 50000,
    "Mid": 100000,
    "Seniors": 50000
  }
];

console.log('Standard Approach');
console.log(data.map((location) => ({
  Population: location.Population
})))
   
console.log('Property Destructuring');
console.log(data.map(({Population}) => ({
  Population
})))

console.log('Using Y && Standard Approach');
console.log(data.map((location) => ({
  y: location.Population
})))

console.log('Using Y && Property Destructuring');
console.log(data.map(({Population}) => ({
  y: Population
})))

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

Express Js EJS Layouts encountered an issue: No default engine was specified and no file extension was included

Hey there! I'm currently experimenting with implementing Express EJS Layouts in my application. However, as soon as I try to include app.use(expressEjsLayouts), an error is being thrown. The application functions perfectly fine without it, but I reall ...

Navigating through an array object

I am currently utilizing react-select and aiming to iterate through an object in order to display it as the select element's value and label: // Within the render method of the component: var myVar = [ this.props.foo.forEach(function(a){ {valu ...

Increment operator `++` in Javascript has two forms: `i

There is a common practice in JavaScript where i++ is used to increment the value of a variable by one. This is commonly seen in loops like the following: for (var i=1; i<=10; i++) { console.log(i); } However, what happens when we use ++i; instead ...

Having trouble getting the jQuery keydown trigger to function properly?

After the document has finished loading, I execute this script: $(function () { $("input").keydown(); }); This script is part of a chrome extension that runs on every page the user visits. However, it does not work on certain websites like Twitter ...

What could be causing the absence of any displayed content in FirBug when typing in the Google Search box?

Many websites with a suggestion box feature utilize AJAX requests to communicate with the server and receive responses. I attempted to intercept the requests made by the Google search box, but the FireBug console did not display anything. However, when us ...

Mastering the Art of jQuery Function Chaining for Beginners

I want to change the name and ID of an element when a radio button is clicked. To avoid duplication of the selector, I tried setting it up this way: $( "#selectOther" ).click(function() { $( "[field=primaryInput]" ).attr('id', "modifiedId", ...

Having difficulty adding multiple items to the state array

I am currently working on a parent component that iterates over an array and passes props to a child component. In the child component (shown below), I have checkboxes with Font Awesome icons for users to mark their selections. When a user checks a box, I ...

Is there a way to effortlessly scroll an element when the CSS overflow property is designated as auto?

I need help with creating a testimonial section where two divs automatically scroll inside a fixed-height container. Currently, only one div is scrolling while the other remains static in my code. I have implemented JavaScript for automatic scrolling wit ...

Creating a React component with a column allowing multiple checkbox selections in NextUI table

Setting up multiple "checkbox" columns in a table using the NextUI table has been my current challenge. Each row should have selectable checkboxes, and I want these selections to be remembered when navigating between pages, running searches, or removing co ...

Troubleshooting problem with autoplay on a Parallax Content Slider in IE8

Does anyone know how to hide the arrows on pictures in IE8 when the mouse is not hovering over them? I've been struggling to find a solution and would really appreciate some help. ...

Send a file from a form using Gatsby to getform.io using the axios library

I am facing an issue with my getform.io form where the file is not getting uploaded properly. The file appears as [] and the files tab remains empty. Upon checking the network tab, I noticed that my request payload includes {email: "[email protec ...

Clickhouse: How to find the date difference while excluding specific days (excluding weekends)

Seems like a simple problem, but I'm struggling to find the solution. I'm currently using ClickHouse version 20.12.5.14. My objective is to calculate the time difference (in minutes) between two datetime values while excluding specific dates stor ...

How to align the navbar toggle button and list items to the right in Bootstrap 5

I'm struggling with a simple html page that has a fixed navbar at the top. Everything looks great when viewed in full-screen mode, with centered links. However, when the page size is reduced, it collapses to a toggle button on the left side. What I re ...

I keep encountering errors from NPM with each command I run

After using npm without any issues in my projects, I am now encountering an error when running commands with npm. The specific error message states that it cannot find a module - '../../package.json'. This is causing my npm commands to fail. ...

"Learn how to trigger an event on a Chart.js chart with Vue.js when it is

Utilizing chart js in combination with vue js, I am able to display data on a dashboard. However, my current objective is to create a function that allows me to click on the chart and navigate to the corresponding table on another view, potentially with fi ...

How to eliminate a specific part of a series of strings in Python

I have a list of over 400 strings that require the removal of the last three characters in each line. rank_f = np.genfromtxt('Ranked Features.dat', delimiter='.',dtype=str) rank_f = rank_f[:,np.array([False, True, False])] An example o ...

Issue encountered while serializing data in next.js when utilizing getServerSideProps function

Encountering An Error Error: The error message "Error serializing .myBlogs returned from getServerSideProps in "/blog"" keeps popping up. I'm facing a problem while attempting to log the data! Initially, when I was fetching data using use ...

Using the class for jQuery validation as opposed to the name attribute

I am looking to implement form validation using the jquery validate plugin, but I am facing an issue with using the 'name' attribute in the html since it is also used by the server application. Specifically, I want to restrict the number of check ...

javascript: restrict the quantity of products

As a beginner in javascript, I am currently working on creating a simple RSS reader. However, I am facing a challenge in limiting the number of feeds to 5 items, especially since the target site may have 100 or more feeds. Here's the code snippet I&ap ...

CodeBlast: A Kid's Game

I'm facing an issue with a puzzle called "A child's play" on Codingame. My coding language is typescript! The task is as follows: Recently, playful programming has become popular in elementary schools where students use assembly blocks to prog ...