What is the process for transforming a JSON object format to another in node.js?

I found myself with a json object structured as follows:

{
    "sample1": {
      "4": 2245,
      "5": 2175,
      "6": 3495,
      "7": 1845,
      ...
      "11.5": 1674,
      "12.5": 1649
    },
    "sample2": {
      "4": 3295,
      "5": 3600,
      "8": 2625,
      "9": 2830,
      ...
      "11.5": 2879,
      "12.5": 3090
    }
}

My goal is to convert it into the following format:

[
    {
        "index": "4",
        "sample1": "2245",
        "sample2": "3295"
    },
    {
        "index": "5",
        "sample1": "2175",
        "sample2": "3600"
    },
    {
        "index": "6",
        "sample1": "3495",
        "sample2": ""
    },
    ....
    {
        "index": "12.5",
        "sample1": "1649",
        "sample2": "3090"
    }
]

In my experience, achieving this in python using pandas is straightforward, but I'm hesitant to mix python scripts with javascript. Are there any simple alternatives to perform this task using Javascript?

Answer №1

const data = {
  example1: {
    4: 2245,
    5: 2175,
    6: 3495,
    7: 1845,
    11.5: 1674,
    12.5: 1649
  },
  example2: {
    4: 3295,
    5: 3600,
    8: 2625,
    9: 2830,
    11.5: 2879,
    12.5: 3090
  },
  example3: {
    4: 3295,
    5: 3600,
    6: 2625,
    9: 2830,
    11.5: 2879,
    12.5: 3090
  }
};

const keys = Object.keys(data);

const mergedInnerKeys = Array.from(
  new Set(
    keys
      .reduce((val, key) => [...val, ...Object.keys(data[key])], [])
      .sort((a, b) => a - b)
  )
);

const result = mergedInnerKeys.map((key) => ({
  index: key,
  ...keys.reduce(
    (v, k) => ({
      ...v,
      [k]: data[k][key] !== undefined ? data[k][key].toString() : ''
    }),
    {}
  )
}));
console.log(result);

Answer №2

const data = {
  "set1": {
    "4": 2245,
    "5": 2175,
    "6": 3495,
    "7": 1845,
    "11.5": 1674,
    "12.5": 1649
  },
  "set2": {
    "4": 3295,
    "5": 3600,
    "8": 2625,
    "9": 2830,
    "11.5": 2879,
    "12.5": 3090
  }
}

const output = Object.keys(data.set1) // Extract all keys from set1
  .concat(Object.keys(data.set2)) // Combine all keys from set2
  .filter((value, index, self) => self.indexOf(value) == index) // Filter out duplicate values
  .sort((a, b) => a - b) // Sort the keys in numerical order
  .map(key => ({ // Create objects for each key in the resulting array
    id: key,
    set1Value: key in data.set1 ? data.set1[key].toString() : '',
    set2Value: key in data.set2 ? data.set2[key].toString() : ''
  }));

console.log(output);

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

How can I efficiently retrieve the name variable of a Quasar (or Vue 3) application?

Is there a way to incorporate something similar in Quasar without having to redefine the variable in every component? <template> <div>Enjoy your time at {{ APP_NAME }}.</div> </template> During the setup of my app with Quasar C ...

stop PHP object from automatic type conversion

class Foo { public $var ; function __construct($value) { $this->var = $value ; } } $myFoo = new Foo('hello'); echo $myFoo->var . '<br>' ; // output : hello // Issue: How can I prevent another prog ...

Exploring the power of Google Maps Radius in conjunction with AngularJS

I am currently developing an AngularJS app that utilizes a user's location from their mobile device to create a dynamic radius that expands over time. You can view the progress of the app so far by visiting this link: . The app is functional, but I a ...

Instructions for obtaining and assigning a reference to a recently cached associated object within the Apollo client InMemoryCache

My data consists of a set of interconnected items like this: book { id ... related_entity { id ... } } Once Apollo caches it, there are two separate cache objects. The related_entity field on book points to an EntityNode object. Everything ...

Endless cycle due to $digest in AngularJS

I recently encountered an issue with an infinite loop involving angularjs $q and promises. Here's the code in question: <a ng-hide="!isTechnician()" class="pull-right" href="#/admin/techniciansState"><span ...

NullPointerException occurs when attempting to assign a value to an array

Encountering a challenge with assigning values to a previously declared array: Enemy[] enemies = new Enemy[100]; Also have a variable tracking the number of spawned enemies: int numEnemies = 0; Attempting to dynamically assign array members to Enemy ...

Is there a way to send data to FastAPI using JavaScript and AJAX?

I am facing an issue while attempting to send data using a request body to my server. I keep receiving an error message that says "value is not a valid dict" with the type_error.dict. The backend, which is built using FastAPI, seems to be functioning prop ...

Delete the file containing Mongoose references

I'm facing an issue with deleting questions when a survey is deleted in the Survey model. Even after deleting the survey, the question remains intact in the database. Survey Schema: let surveyModel = mongoose.Schema( { Title: String, T ...

What is the reason for the viewport in three.js renderer not functioning properly on IE browser?

Try setting the viewport with different coordinates: this.renderer.setViewport(50, -50, this.width, this.height); What could be causing issues with IE browser compatibility? ...

Flutter does not recognize String as a subtype of Map<String, dynamic>

I am currently working on converting a JSON response into an object. JSON Response: {"Data":"{\"IdToken\":\"eyJraWQiOiJxazZwYk9GZVdPWnRTbWorczlqMng2cDN5bUFUcXdDTlhMQ09Ic1JIOFNFPSIsImFsZyI6IlJTMjU... Model Clas ...

Connect or disconnect an element to a JavaScript event handler using an anonymous function

I'm stuck on a basic issue... I have a custom metabox in my WordPress blog, and here's my event handler: jQuery('tr input.test').on('click', function( event ){ event.preventDefault(); var index = jQuery(this).close ...

What is the best way to include icons in a list item on the left, center, and right side?

I'm in the process of developing an Ionic app that integrates with the Spotify API. One feature I want to include is a widget that displays three icons in a list item: the left icon for the last song, the center icon for play/pause functionality, and ...

Angular: When $scope variable is modified, a blank page issue arises

In my Angular application, I have a template called viewAll.html that is displayed after clicking on a link. This template fetches data via AJAX using scope variables. However, I encountered an issue where updating these scope variables through AJAX cause ...

Learn the step-by-step process of cropping and zooming an image using the react-image-crop

I am looking to implement zooming and cropping functionality for an image using react-image-crop instead of react-easy-crop. Currently, the cropping does not take into account the zoom level set by ReactCrop's scale property. I want to be able to zo ...

Which event in the listbox should I trigger to adjust the scroll position?

My webpage includes a listbox inside an update panel. I've managed to capture the scroll position, but now I'm facing difficulty in identifying the right javascript event to call my function for setting the scroll position after the update panel ...

React Hook causing excessive renders due to custom UseLayoutEffect hook for bounding box calculation

Currently, I am developing a feature to generate a hub and spoke diagram. This involves having a central div with other divs surrounding it, all connected by SVG lines. For a simplified code example, you can check out this code sandbox. To achieve this fu ...

Organize a Javascript array by grouping it based on a specific field and

I have an array that I need to group by the createdAt value. [ { "createdAt": "2021-05-17T14:55:29.836Z", "machine": { "label": "MAQ_100", }, }, { "createdAt": "2021-03-10T13:22:45.694Z", "machine": { ...

What is the process for loading an external file within an npm script?

Objective: Testing the linting process of specific components within the source code, without affecting all files. I want to streamline the linting process by running a single command that covers multiple folders specified in a configuration file: //pack ...

Troubleshooting Recursive Logic Problem with hasOwnProperty in JavaScript and JSON

JSON data with a specific problem highlighted by the comment // doesn't get parsed currently: var oarsObject = [{ "coordinateReferenceSystem": "26782,15851 <-- not in a value", "positionReferenceType": "geogWgs84", "geogWgs84": ...

Refresh a specific div element within an HTML file when the AJAX call is successful

After uploading the image, I want it to be displayed right away. To achieve this, I am looking to refresh the div with id="imagecontainer" within the success function of my ajax call. However, I would prefer not to rely on ("$id").load("href") as it does ...