Converting a JSON object into an array of objects

I am looking to transform the following JSON structure

let data = {
  item1: [11, 12, 13, 14, 15],
  item2: [16, 17, 18, 19, 20]
}

into this specific format using JavaScript's native functionalities of arrays or objects (compatible with all web browsers)

[{
  item1: 11,
  item2: 16
},{
  item1: 12,
  item2: 17
},{
  item1: 13,
  item2: 18
},{
  item1: 14,
  item2: 19
},{
  item1: 15,
  item2: 20
}]

I attempted to achieve this using a for loop and here is the code snippet I came up with:

let keys = Object.keys(data);
let transformedData = [];
for(let i = 0; i < keys.length; i++){
   let key = keys[i];
   for(let j = 0; j < data[key].length; j++){
      if(i === 0){
        let obj1 = {};
        obj1[key] = data[key][j];
        transformedData.push(obj1);
    }else{
        let obj2 = transformedData[j];
        obj2[key] = data[key][j];
    }    
  }
}

Answer №1

If you want to achieve this, you can utilize the Array.prototype.reduce() method.

To accomplish this task, iterate through the elements of the test1 array and add a new object to the accumulating array with properties test1 and test2 along with their corresponding values.

let init = {
  test1: [1, 2, 3, 4, 5],
  test2: [6, 7, 8, 9, 10]
};

let keys = Object.keys(init);
let key1 = keys[0];
let key2 = keys[1];

let result = init[key1].reduce((acc, curr, i) => {
  acc.push({
    [key1]: curr,
    [key2]: init[key2][i]
  });

  return acc;
}, []);

console.log(result);

At present, the reduce() method is supported in most modern browsers. If you need support for all browsers, consider using a for loop instead of Object.keys(). Iterate through object properties or use a polyfill.

let init = {
  test1: [1, 2, 3, 4, 5],
  test2: [6, 7, 8, 9, 10]
};

let keys = [];

for (let key in init) {
  if (init.hasOwnProperty(key)) {
    keys.push(key);
  }
}

let key1 = keys[0];
let key2 = keys[1];

let result = [];

for (let i = 0; i < key1.length; i++) {
  result.push({
    [key1]: init[key1][i],
    [key2]: init[key2][i]
  });
}

console.log(result);

Answer №2

To achieve the desired result, a combination of for...in and Array.forEach can be used in just a few lines of code. For broader browser support, it's recommended to use var instead of let. Browser compatibility reference

var init = {
  test1: [1, 2, 3, 4, 5],
  test2: [6, 7, 8, 9, 10]
}

var result = []
for (var key in init) {
  init[key].forEach(function (item, index) {
    result[index] ? result[index][key] = item : result[index] = { [key]: item }
  })
}

console.log(result)

A simpler approach would be initializing the result with empty objects to avoid using ternary statements:

Note: This method is not compatible with IE11 due to lack of support for Array.fill()

var init = {
  test1: [1, 2, 3, 4, 5],
  test2: [6, 7, 8, 9, 10]
}

var result = new Array(Object.keys(init)[0].length).fill().map(Object);
for (var key in init) {
  init[key].forEach(function(item, index) {
    result[index][key] = item
  })
}

console.log(result)

When implementing this method, be cautious about creating an array with Objects that refer to the same memory object: Reference issue with Array.prototype.fill() and objects

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

Transmit JSON from PHP to an autocomplete feature and include a data attribute in the input field

[{ "id": "39", "name": "John Doe", "code": "060400000" }] $(document).on("input", ".autocomplete", function(event) { var name = $(this).prop('id').split('_').pop(); $(".autocomplete").autocomplete({ source: function(request, respo ...

How to properly Open a "div" Element by its ID in ReactJS

Today, I want to share an issue that I've been facing. To simplify things, I have mapped a BDD, The result of this mapping is displayed in multiple cards, There's a button that when clicked opens up more details on the map, But here's wh ...

Initial position of jQuery slider

A while back, I came across some slider code on a website and copied it. Unfortunately, I can't seem to locate the source now. Here is the code snippet: slides.min.jquery.js $(function(){ $('#slides').slides({ preload: true, ...

How can I convert a series of numerical values into a numpy array?

Is there an alternate method to convert '1 2 3' into a numpy array [1, 2, 3] besides using np.fromstring()? Maybe through np.array() instead? Appreciate any insights. Thanks! I attempted the following: x = '1 2 3' x = np.fromstring(x, ...

jquery plugin for creating Excel-like filters

I am in the process of creating Excel-like filtering for my dynamic table. To achieve this, I am utilizing a jQuery plugin that can be found at https://github.com/chestercharles/excel-bootstrap-table-filter. The reason why I chose this plugin is because it ...

Transform the jQuery UI Slider to be clickable rather than draggable

Currently using jQuery UI 1.10.3 and aiming to create a slider widget that is not draggable. The intention is for the user to click on specific values along the slider instead. I previously attempted using eventDefault in the slider's start method, b ...

Is it possible for Cypress to execute test files that are imported from outside of the Cypress folder

Currently, I am developing an E2E test framework using Cypress and encountered an issue while trying to import spec files from locations outside the traditional Cypress directory structure (which includes directories for fixtures, integration, plugins, and ...

What is the method to eliminate waitedMS and ok values from the output of a MongoDB aggregation query?

I have a MongoDB PHP application where I am using aggregation commands. Here is the code snippet: <?php $query = array('$or' => array( array('employeeList'=>array('$exists' => false)), array('emplo ...

Getting the elements from multiple arrays in Python

It seems like a simple task, but I'm not quite sure how to tackle it. Let's say we have three different arrays: x = [1, 2, 3, 4, 5] y = [1, 3, 5, 7 ,9] z = [1, 5, 10, 15, 20] So, the question is: How can I loop through each element of these arr ...

Tips for storing information from Json using Alamofire and SwiftyJSON?

My attempt to save "author" data to a global variable named "authors" from the JSON file (Link: "") using two libraries seems to be working only within the trailing closure of func Alamofire.request(url).responseJSON. However, when I try to access the "aut ...

What strategies can be employed to tackle the challenges posed by Ajax asynchronous calls?

Beginner in JavaScript - I just wanted to mention that upfront. Take a look at this straightforward example where I aim to create X number of gauges, with the value of X being retrieved from JSON using an Ajax call. <body> <div id="gServer"> ...

Retrieve the date one week prior to today's date in Node.js and format it in Mysql style

I need to find the exact date from one week ago in SQL format using Node.js. I attempted a similar solution as described here - How to get yesterday date in node.js backend? but unfortunately it's not working for my specific case. ...

The abort() function in Chrome can trigger an Undefined Error

When dealing with race conditions, I implement the following code to throttle get requests: if (currentAjaxRequest !== null) { currentAjaxRequest.abort(); } var query_string = getQuery(); currentAjaxRequest = ...

display JSON data beautifully on a webpage using Express

I am trying to display a large JavaScript object in a visually appealing format on my browser window using Express. I have experimented with using res.json() and res.send() with pretty print enabled in Express, but it seems that this method only works fo ...

Error: The function this.$.AjaxPost.go is missing or not recognized in the core-ajax module

Recently, I created an HTML page for handling Password Reset functionality on our website. We have decided to make POST calls to the server and are implementing it using polymer. Below is a snippet of the code: <dom-module id="user-password-reset"> ...

Issues with object changes not reflecting in Vue.js 2.0 component rendering

I am facing an issue where my object is not updating immediately after a click event. It appears that a manual refresh or clicking on another element is necessary for the changes to take effect. How can I ensure that the object updates without the need for ...

What is the best way to transmit a Blob object to the server without it arriving empty?

I'm currently facing an issue where I am attempting to send a Blob object containing video data to my server for upload to my S3 storage. However, the Blob is arriving as an empty object on the server side. const blob = new Blob(videoChunks, { t ...

Is it possible to associate an unidentified JSON with a JsonObject in AspNetCore?

Having some trouble binding a dynamic json input to a JsonObject in AspNetCore. It doesn't seem to be working as expected. ("The JSON value could not be converted to System.Collections.IEnumerable. Path: $ | LineNumber: 1 | BytePositionInLine: 11.") ...

Display a modal before leaving the page?

I need to display a modal message when a user navigates away from the page, triggered by a successful AJAX call. The issue is that if the message loads too quickly, the user may not have enough time to read it before being directed to another page. This is ...

Tips for choosing the desired test to execute with Nightwatch Programmatic API

Currently, I am in the process of developing a web application that enables me to execute Nightwatch tests through a visual interface. At this point, I have successfully been able to run all my tests using a post request from my web app utilizing the Nig ...