Combining arrays in JavaScript to form object values with lodash

In my current project, I am attempting to manipulate JavaScript object arrays using lodash. The goal is to stack array values from different objects and map them to corresponding objects in a new array. Here's an example of what I'm working with:

olympicmedals = {
    '2008': [{'country': 'China', 'golds': 51}, {'country': 'USA', 'golds': 36}],
    '2012': [{'country': 'China', 'golds': 38}, {'country': 'USA', 'golds': 46}]
}

The desired outcome is as follows:

olympicmedals = [
    {'country': 'China', 'golds2008': 51, 'golds2012': 38},
    {'country': 'USA', 'golds2008': 36, 'golds2012': 46}
]

I am looking to achieve this for the purpose of creating charts in amCharts, which can be seen here (click 'View Demo Source' therein).

My understanding is that the _.map() function may be useful for this task, but I am not entirely sure how to proceed. Any guidance would be greatly appreciated. Thank you!

Answer №1

To simplify the process, you can utilize the forEach() loop for iterating through objects within arrays to efficiently add years as keys. This approach offers flexibility in handling multiple object properties beyond just gold medals.

const data = {
  '2008': [{
    'country': 'China',
    'golds': 51,
    silver: 10
  }, {
    'country': 'USA',
    'golds': 36
  }],
  '2012': [{
    'country': 'China',
    'golds': 38
  }, {
    'country': 'USA',
    'golds': 46,
    bronze: 10
  }]
}

const result = []
Object.keys(data).forEach((e) => {
  const that = this;
  data[e].forEach((a) => {
    if (!that[a.country]) {
      that[a.country] = {
        country: a.country
      }
      Object.keys(a).forEach((key) => {
        if (key != 'country') that[a.country][e + key] = a[key]
      })
      result.push(that[a.country])
    } else {
      Object.keys(a).forEach((key) => {
        if (key != 'country') that[a.country][e + key] = a[key]
      })
    }
  })
}, {})

console.log(JSON.stringify(result, null, 4))

Answer №2

Though a bit delayed, here's an alternative method using map and reduce:

data = {
    '2008': [{'country': 'China', 'golds': 51}, {'country': 'USA', 'golds': 36}],
    '2012': [{'country': 'China', 'golds': 38}, {'country': 'USA', 'golds': 46}]
}

const countriesList = data[Object.keys(data)[0]].map(element => element.country)

const outcome = countriesList.map(country => {
  return Object.keys(data).reduce((previous, year) => {
    previous[`golds${year}`] = data[year].find(item => item.country === country).golds
    return previous
  }, {country})
})
console.log(outcome)

When handling this type of conversion task, I prefer obtaining the necessary column information first and storing it in a variable (`countriesList`), which can then be used to filter or find the relevant data later on. While there may be methods to achieve this without any local state, readability might become compromised.

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

Design a collection of image icons to use as a toolbar in a web

I am in the process of creating a basic online application that allows users to select images from a toolbar (or storage box) and drag them onto a canvas. I am relatively new to web development but have figured out the drag and drop functionality. Right no ...

The non-generic nature of Typescript's Type Object is a distinguishing feature

I've been attempting to define a type for an Object, but I just can't seem to get it right. Below is what I have so far: private myObject:Object<MyType>; this.myObject = {id : 'test'}; interface MyType { id : string; } Howe ...

In order to display the particle-slider logo effect, the JavaScript on the page needs to be refreshed

I have a website frontend integrated from WordPress using an HTML 5 Blank Child Theme. The site features a logo effect utilizing particle slider for screen sizes greater than 960px, and a flat logo image for screen sizes less than 960px. Everything works p ...

Optimal method for reorganizing a 2D numpy array based on a separate 2D index array

Summarized What is the most efficient way to rearrange elements in a 2D array in Python 3.6 using Numpy, based on indices from another 2D array of the same shape? Details Let's say we have two 9 x 5 arrays named A and B: import numpy as np A = np.ar ...

What is the best way to display time instead of angles in highcharts?

Hey there! I'm currently working with highcharts and I have a polar chart where I want to display time on the y-axis instead of angles. Here's what I've tried so far: On the x-axis, I have angles and I've set tickInterval: 45,. How can ...

Is there a more efficient method for handling this JSON dataset?

After delving into Sitepoint's "Novice to Ninja" and starting to explore jQuery, I can't help but question if there is a more efficient way to write the code I've put together. The resounding answer appears to be "yes." All these cumbersome ...

Retrieve a particular nested array value and print it using PHP

How can I retrieve a value from an array based on the current user's email address in WordPress? The array is decoded using the following code: $link= json_decode($xml, TRUE); I have a simple logic to fetch and display the current user's email: ...

A beginner's guide to using Jasmine to test $http requests in AngularJS

I'm struggling with testing the data received from an $http request in my controller as I don't have much experience with Angular. Whenever I try to access $scope, it always comes back as undefined. Additionally, fetching the data from the test ...

Is it necessary to confirm the validity of url.format(urlObject)?

I have been exploring the NodeJS URL API and am particularly interested in the url.format(urlObject) method. My goal is to develop a function that first validates the urlObject before using the format function, and throws a TypeError if any of the key/valu ...

Providing dynamic string outputs depending on the current date using AngularJS

I set up an advent calendar that reveals a new question every day, but currently the questions aren't showing up. Here's the code I have: The controller located in app.js: .controller('textCtrl', function($http) { this.data = {}; ...

If all input values within every li element are equal to zero in jQuery

Currently, I am facing an issue that I need to solve. I have multiple inputs and my goal is to check if each input has a value of 0 and is also checked. After spending an entire day searching for a solution, I am still clueless about how to proceed. I att ...

What is the process of encoding JSON in PHP using jQuery Ajax to send post data?

I created an HTML form to submit data to a PHP file upon hitting the submit button. $.ajax({ url: "text.php", type: "POST", data: { amount: amount, firstName: firstName, lastName: lastName, email: email }, ...

JavaScript does not recognize jsPDF

After importing the jsPDF library, I attempted to export to PDF but encountered a JavaScript error stating that jsPDF is not defined. I tried various solutions from similar posts but none of them seemed to work for me. You can find the fiddle here: https ...

Sending dynamic data through AJAX to a CodeIgniter controller is a common task that allows for seamless

Can anyone help me with retrieving data from a looping form in CodeIgniter? The form works fine, but I'm struggling to fetch the looping data in the controller. Here's my view (form): <form action="#" id="ap_data"> <div class="table-r ...

Obtain an array dynamically through a manufacturing plant

I'm currently working on extracting information from a factory and displaying it in a dynamic manner. Previously, I used the following approach: <div class="articlePage"> <h4> {{ posts[0].title }} </h4> <span style="color: # ...

Understanding the performance of video in threejs when using getImageData

Edit; Check out the working codepen (you'll need to provide a video file to avoid cross-origin policy) https://codepen.io/bw1984/pen/pezOXm I'm currently trying to adapt the amazing rutt etra example from to utilize video (using threejs), but ...

Lost variable during the ajax call

Encountering a peculiar issue while attempting to pass a variable as a parameter to a nested ajax request callback: $('form').on('submit',function(e){ $.ajaxSetup({ header:$('meta[name="_token"]').attr('conte ...

Issue with Vue3: The imported module is not defined

Update: I recently downgraded vue-cli to version 4.5.19 and now the code is functioning properly. It seems like there might be an issue related to vue-cli or its dependencies. I encountered a problem while working on a simple vue.js project using vue-cli. ...

using VueJS, learn how to dynamically apply text to a data variable based on certain props

I'm facing an issue with conditional value assignment to the data variable based on props. The ternary operator is causing errors in my code. Here's a snippet for reference: <template> <div class="absolute left-3 top-1/2"> ...

Encountering an error: [nsIWebProgressListener::onStatusChange] when utilizing jQuery AJAX within a click event?

Greetings! I am currently learning how to implement AJAX with jQuery to load an HTML document into a div element within another HTML document. Here is the approach I am using: function pageload() { $.ajax({ url: 'Marker.aspx', ...