Creating an object in Javascript using a combination of arrays and variables

I have two distinct sets of arrays that need to be combined into an object.

x1 = ['US', 'UK', 'China'];
y1 = [1,2,3];
name1 = 'CO2';

x2 = ['US', 'UK', 'China'];
y2 = [4,5,6];
name2 = 'GHG';

The x1 and x2 arrays always contain the same values.

This is the desired outcome:


[{'country': 'US', 'CO2': 1, 'GHG': 2},
{'country': 'UK', 'CO2': 2, 'GHG': 5},
{'country': 'China', 'CO2': 3, 'GHG': 6}]

I attempted to construct the object like this:

var result = {};

x1.forEach(function (key,i) { result.country = key, result[name1] = y1[i] });

However, it only displays the last value:

{country: "China", CO2: 3}

I also tried the following approach:

x1.forEach((key, i) => result[key] = y1[i]);

In this case, the name is not included in the output.

The entire process should be dynamic, which poses additional challenges as I cannot manually assign values as needed.

Answer №1

const countriesList1 = ['US', 'UK', 'China'];
const emissions1 = [1, 2, 3];
const pollutant1 = 'CO2';

const countriesList2 = ['US', 'UK', 'China'];
const emissions2 = [4, 5, 6];
const pollutant2 = 'GHG';

const data = countriesList1.map((country, index) => ({
  country,
  [pollutant1]: emissions1[index],
  [pollutant2]: emissions2[index]
}));

console.log(data);

Answer №2

One approach you might consider is iterating through the x1 array and utilizing the data to construct a new result array.

var myResult = {}
for(j = 0; j < x1.length; j++) {
  myResult[j] = {}
  myResult[j]["region"] = x1[j]
  myResult[j][label1] = y1[j]
  myResult[j][label2] = y2[j]
}

console.log(myResult)

Answer №3

To achieve this, you can implement the following solution without using a variable x2:

function generateObjects(x1, y1, y2, property1, property2){
  var firstObj = {},
         secondObj = {},
         thirdObj = {};
  var finalResult = [firstObj, secondObj, thirdObj];
  finalResult.forEach((obj, index) => {
    obj.country = x1[index];
    obj[property1] = y1[index];
    obj[property2] = y2[index];
  })

  return finalResult;
  
}

Your current code is only retrieving the last value because it keeps overriding the values of the objects within the forEach loop.

Answer №4

const countries = ["USA","UK","China"];
const emissions1 = [1,2,3];
const gas1 = "CO2";
const emissions2 = [4,5,6];
const gas2 = "GHG";

const results = countries.map((country, index) => ({
  country: countries[index],
  emission1: emissions1[index],
  emission2: emissions2[index]
}));

console.log(results)

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

Guide on deploying Google App Script add-ons on Google Workspace Marketplace

Recently delving into Google App Script, I've taken my first steps in coding within the platform. Utilizing the deploy option provided by Google App Script, I successfully launched my app. However, upon deployment, I encountered difficulty locating my ...

Comparing Angular6, ReactJS, and VueJS: Which JavaScript framework

As I embark on my journey into the world of technology, I am seeking recommendations on where to begin. I am a newbie in this realm and would greatly value your bold suggestions. I am particularly interested in starting with Nodejs as a back-end technolo ...

Obtain GPS coordinates (latitude/longitude) from a Google map by dropping a marker on the

Is there a straightforward script that can load a Google Map and, when clicked, display a marker that saves the latitude and longitude values to a variable? Does anyone know if there is an existing PHP solution for this functionality? Appreciate any help ...

Using jsTree to Connect to Objects in a Domain

I'm looking for a way to link each node in my tree with a domain object. Previously, I was passing HTML data and storing the domain object manually using jQuery data: $('li node description').data('obj', my_domain_object); Howeve ...

How to retrieve the user-agent using getStaticProps in NextJS

Looking to retrieve the user-agent within getStaticProps for logging purposes In our project, we are implementing access and error logs. As part of this, we want to include the user-agent in the logs as well. To achieve this, we have decided to use getSta ...

Is there a way to refresh/reload an Angular 2 application without relying on window.location.reload()?

Is there a way to refresh or reload an Angular application without using window.location.reload()? I am looking to achieve this after logging out and then logging back in. My goal is to load the initial root component, which is typically loaded during ap ...

Angular failing to display base64 image when being added to the application

I created a program where users can upload an image, preview it, and then add it to a list by clicking a button. The preview functionality is working fine, but when attempting to add the image to the next row in the table, nothing happens... Question Ca ...

Selecting from dropdown menu showing limited options extracted from XML data

Need help with populating a combo box named combo_assembly using Ajax. The function to achieve this is: function populate_combo_assembly(xmlindata) { var xmldata = xmlindata.getElementsByTagName('Assemblies'); if(xmldata.length <= 0) { ...

Can a div with float: left; be centered?

Currently, I am attempting to create a dock (similar to the iOS dock) for my website. Below is the full code that I have implemented: function addPrevClass(e) { var target = e.target; if (target.getAttribute('src')) { // check if it is img ...

React Component - Element with an undefined value

When I tried implementing an Ionic Modal as a React Component, I encountered the following error message: Type '({ onClose, tipo }: PropsWithChildren<{ onClose: any; tipo: number; }>) => Element | undefined' is not assignable to type & ...

Is there a way to troubleshoot a webpack-compiled npm module effectively?

Looking to debug an npm module compiled with webpack by setting breakpoints and stepping through the code? The issue may arise when importing the module locally using npm link, as only the compiled code is accessible for debugging from the application. W ...

Insert a fresh item into the existing unordered list

Every time I enter something in the prompt, it shows up as "undefined". What I actually want is for whatever I type into the prompt to be added as a new list item. For instance, if I type "Food" in the prompt, I expect to see "Food" appear on the second li ...

The current limitation of the Dev.to API restricts the display of only the most recent

For the past 3 years, I've integrated Dev.to's public API into my portfolio to display all of my articles. However, after transitioning my entire portfolio to ReactJS and SaSS from native HTML, CSS, and JS, it now only shows my latest 30 articles ...

Autocomplete for Converting Postal Codes to Cities

I'm currently working on a project that involves two input fields, as shown below: <div class="form-group{{ $errors->has('plz') ? ' has-error' : '' }}"> <label for="plz" class ...

Tips for changing array items into an object using JavaScript

I am working with a list of arrays. let arr = ["one","two"] This is the code I am currently using: arr.map(item=>{ item }) I am trying to transform the array into an array of sub-arrays [ { "one": [{ ...

Sending data with React using POST request

Currently in my React application, I have a form that includes fields for username and password (with plans to add "confirm password" as well). When submitting the form, I need it to send JSON data containing the email and password in its body. The passwo ...

Could anyone clarify the reason behind the success of one function while the failure of the other?

Currently delving into the world of React, I decided to follow along with the Road To React book. In this guide, the author presented this code const List = (props) => ( props.list.map(item => ( <div key={item.objectID}> & ...

Libraries that provide webkit support for all browsers

Looking for a library that supports CSS webkit across various browsers, including older ones like ie6. Preferably written in JavaScript. Any recommendations? ...

Using jQuery to handle multiple AJAX XML requests

Currently, I am working on developing a JavaScript XML parser using jQuery. The idea is that the parser will receive an XML file containing information along with multiple links to other XML files. As the parser runs, it will identify tags within the file ...

Leveraging the power of the Google API within the Dojo module

Is it possible to integrate Google Maps API within a Dojo Toolkit module in the following way? define(["dojo/dom"], function (dom) { var input = dom.byId("searchBox"); var autocomplete = new google.maps.places.Autocomplete(input, options); } ...