Modify the layout of a JSON data structure

Here is an example of an array:

let array =  [
      {1: {
        "date": "2014-04-23 00:00:00",
        "volumetrie": "22458"
      }},
      {2: {
        "date": "2014-05-02 00:00:00",
        "volumetrie": "30585"
      }},
      {3: {
        "date": "2014-03-27 00:00:00",
        "volumetrie": "49536"
      }}
    ]

I want to transform it into this format:

let array =  [
      {
        "date": "2014-04-23 00:00:00",
        "volumetrie": "22458"
      },
      {
        "date": "2014-05-02 00:00:00",
        "volumetrie": "30585"
      },
      {
        "date": "2014-03-27 00:00:00",
        "volumetrie": "49536"
      }
    ]

I attempted to make the change using this code:

array.forEach(function(e){
          newData.push(e);
        });

Unfortunately, this approach did not work due to push not being supported.

Another method I tried was:

let newData = {};
        array.forEach(function(e){
          newData = {...newData, ...e};
        });

Despite my efforts, this solution was also unsuccessful. Do you have any suggestions on how to achieve the desired result?

Answer №1

To retrieve a flat array containing the values of the objects, you can use the following code:

let data = [{ 1: { date: "2014-04-23 00:00:00", volume: "22458" } }, { 2: { date: "2014-05-02 00:00:00", volume: "30585" } }, { 3: { date: "2014-03-27 00:00:00", volume: "49536" } }],
    resultArray = data.flatMap(Object.values);

console.log(resultArray);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

If each item in the array has only one enumerable property, you can achieve this using map and Object.values:

array = array.map(obj => Object.values(obj)[0]);

Here is a live example:

let array =  [
  {1: {
    "date": "2014-04-23 00:00:00",
    "volumetrie": "22458"
  }},
  {2: {
    "date": "2014-05-02 00:00:00",
    "volumetrie": "30585"
  }},
  {3: {
    "date": "2014-03-27 00:00:00",
    "volumetrie": "49536"
  }}
];
array = array.map(obj => Object.values(obj)[0]);
console.log(array);
.as-console-wrapper {
    max-height: 100% !important;
}

Alternatively, check out Nina's solution using flatMap, which offers an elegant approach.

Answer №3

To transform each item in the array, you can simply extract the value of the first key from each original item:

let array =  [
  { 1: {
    "date": "2014-04-23 00:00:00",
    "volumetrie": "22458"
  }},
  { 2: {
    "date": "2014-05-02 00:00:00",
    "volumetrie": "30585"
  }},
  { 3: {
    "date": "2014-03-27 00:00:00",
    "volumetrie": "49536"
  }}
];

let formatted = array.map(obj => { for (let key in obj) return obj[key]; });

console.log(formatted);

Answer №4

Give this a shot:

const previousRecords = [
    {1: {
        "date": "2014-04-23 00:00:00",
        "volume": "22458"
    }},
    {2: {
        "date": "2014-05-02 00:00:00",
        "volume": "30585"
    }},
    {3: {
        "date": "2014-03-27 00:00:00",
        "volume": "49536"
    }}
];
const updatedRecords = [];

for (let index = 0; index < previousRecords.length; index++) {
    updatedRecords[index] = previousRecords[index][index+1];
}

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

Steps for verifying the following number and contrasting it with the previous one

I have an array containing numbers with a total size of 14. The array is filled with -1 in blank spaces, while the rest of the numbers are like this: [2,3,4,7,8, -1, -1...]. To ensure that the numbers are exactly one apart, I need to compare them and find ...

When iterating through HTML Elements using the forEach method, the getElementsByClassName function is not capable of targeting these specific elements

Allow me to elaborate, although you will grasp the concept better once you see the actual code. I am retrieving my div elements using the getElementsByClassName function and then converting them into an array using Array.from(). As I iterate through this a ...

What is the process for configuring the Jackson provider with the Wink client?

Attempting to build a toy application that has the potential of evolving into a real one, I've encountered an issue involving Wink and Jackson. My setup consists of two applications: one utilizing wink-server on jetty to provide JSON data efficiently, ...

Guide on Updating the ColModel Dynamically in JAVASCRIPT/HTML using clearGridData, setGridParam, and reloadGrid Functions

I am trying to figure out how to dynamically change the colmodel of my grid using a function that is called by a SELECT. The reason for this is because my grid has different periods and needs to display either cost or tons based on user selection. Below i ...

Combining JSON arrays based on property matches in Node.js

I am working with two JSON arrays in Node.js. const arr1 = [{id: 1, name: 'X'}, {id: 2, name: 'Y'}, {id: 3, name: 'Z'}, {id: 4, name: 'W'}]; const arr2 = [{id: 1, value: 80}, {id: 2, value: 30}, {id: 3, value: 76}] ...

Retrieving information from a JSON file utilizing an Interface

For the purpose of learning, I am developing a small Ionic app where I want to load data from a JSON file and map it to an interface that defines the data structure. However, I am facing challenges in achieving this: import { Component } from "@angular/co ...

What is the method of using "*" as the value for allowedModules in a jsreport configuration file to enable all modules?

I am having an issue when trying to generate a report using jsreport STUDIO. The error message I received is as follows: An error occurred - Error during rendering report: Unsupported module in scripts: request. To enable require on a particular module, ...

Ways to halt the repetition of clicking the like button on my social media posts

I've been working on a new post system that allows users to like posts. Everything seems to be in order except for one issue - when iterating through the likes table from the post-like relation, the like button is being duplicated even with added cond ...

Is there another option besides PHP not being compatible with JavaScript?

I'm looking to dynamically change the properties of a div, so I've turned to using the jquery.keyframes plugin. The second class currently has a low-res blurred background image from the croploads directory. Now my goal is to switch it out for a ...

Encountering the "Component resolution failed" error in Vue 3 when using global components

When I declare my Vue components in the top level HTML file, everything works fine. Here is an example: <body> <div class='app' id='app'> <header-bar id='headerBar'></header-bar> ...

Adding two input values using jQuery

Here is the function compute() that I am working with: function compute() { if ($('input[name=type]:checked').val() != undefined) { var a = $('input[name=service_price]').val(); var b = $('input[name=modem_pric ...

A guide on incorporating user input and output in Javascript using React and Material UI

Currently, I am working on a project that requires ReactJS and Material UI. My main goal is to implement the code provided below in just a single JS file. Is there a way to modify this code to meet my formatting requirements? //js file function calculat ...

I encountered an issue while trying to use jshint with a simple hello world script, receiving the error message: "line 0, col 0, Bad option: 'script'."

This is a basic introduction to my coding journey. function greet() { return 'Hello world'; } Here is the jshint setup I am using: { "browser": true, "browserify": true, "devel": true, "script" ...

Tips for transforming a JSON response into an array with JavaScript

I received a JSON response from an API: [ { "obj_Id": 66, "obj_Nombre": "mnu_mantenimiento_de_unidades", "obj_Descripcion": "Menu de acceso a Mantenimiento de Unidades" }, { "obj_Id": 67, "ob ...

The inner radius remains constant in the Chart.js Doughnut Chart

I've been trying to create a half doughnut chart using Chart.js, similar to the image linked below. However, I'm having trouble adjusting the thickness of the pie chart. Despite using the innerRadius property, it's not producing the desired ...

Optimizing Require.js File for Efficient Loading

I have successfully implemented require.js with multiple individual files: require(['app/login/Login'], function (app) { new app.Login(); }); Everything is functioning as expected, with each module loading when needed. Recently, I have opti ...

Adding Data to MySQL Database Using Android Studio

Currently, I am working on adding records to MySQL using Android Studio. After successfully inserting records in my API, it returns a JSON result like this: {"status":"success"} I would like to know how I can incorporate and write the code in my Android ...

Executing JavaScript code using an HTML form submission

Greetings, I have implemented an HTML form on my website for user login using AJAX (jQuery), but I am encountering some issues. Below is the JavaScript code: function validateLoginDetails() { $('[name=loginUser]').click(function() { ...

Ways to activate a stylish pop-up box using an input field (when focus is removed)

While attempting to activate Fancybox upon the user shifting focus away from an input field containing a value greater than 25, everything seems to be in order with the focus out and value checking code. Nevertheless, when Fancybox is triggered, the follow ...

What is the best way to access dropdown sub-menu options from a complex multi-level navigation bar

Struggling to figure out how to open my dropdown sub-menu using CSS. Hoping to make it so the user can open it by hovering over the corresponding tag. I attempted to use #lablinksDD to trigger the opening of #ddSbMenu when hovered over #menuDD with #labLin ...