Reorganizing JSON arrays with JavaScript

Exploring the realm of JSON notation as a newcomer has presented me with an intriguing challenge. I find myself in a situation where I need to reformat the current database format to align with a new structure suitable for importing into a project timeline graph.

The initial JSON format retrieved from the database is as follows:

[
{
  "name":"5-HP-N/A-N/A-F8",
  "node":{
     "name":"5",
     "id":14
  },
  "timeline":{
     "epc":null,
     "m1":null,
     "m2":null,
     "m3":1554087600000,
     "m4":1593572400000,
     "m5":1625108400000,
     "m6":1641006000000,
     "m7":1656644400000
  },
  "fab":{
     "name":"F8",
     "id":1
  }
},

However, the desired JSON format essential for graph display is structured as follows:

    {
  'start': new Date(value from epc or first non-null milestone),
  'end': new Date(value from m1 or first non-null milestone),  // end is optional
  'content': 'label from start Date milestone',
  'group' : ' value from name field above 5-HP'
  'classname' : ' value from start Date milestone' 
});

I am currently in the process of crafting a function that can effectively achieve this objective. While only epc, m1, or m2 may hold null values, it is imperative to inspect these conditions to determine event ranges' creation and termination points. What would be the most efficient approach to reformat this json data (preferably sourced from an external json sheet)?

Edit: Grateful for the assistance provided so far! It now appears clearer how the reformatting works. On reflection, my initial explanation was not as exhaustive. My actual requirement involves multiple class items per "group".

The ultimate goal is for these items to be displayed sequentially on a timeline graph 'group' line. Consequently, I am exploring ways to generate distinct objects for each array element detailed above.

In practice, the first object's start date would correspond to m3, while its end date would align with m4. Subsequently, the consecutive object would share the same group as the preceding one (5-HP...), initiating at m4 and concluding at m5...and so forth. This sequence persists until m7 (always an end date but never a start date) is reached.

This complexity introduces various conditions, making the looping process less straightforward.

Answer №1

Take a look at the working example here: http://jsfiddle.net/K37Fa/

It appears that your input data is in the form of an array, so I created a loop to handle that. If it's not an array, you can view another fiddle where the input data is a simple object: http://jsfiddle.net/K37Fa/1/

var i 
  , result = [],
  , current
  , propCounter
  , content = [ { "name":"5-HP-N/A-N/A-F8", "node":{ "name":"5", "id":14 }, "timeline":{ "epc":null, "m1":null, "m2":null, "m3":1554087600000, "m4":1593572400000, "m5":1625108400000, "m6":1641006000000, "m7":1656644400000 }, "fab":{ "name":"F8", "id":1 } }],
  
// Function to retrieve milestone from object
getMileStone = function(obj) {
  propCounter = 1;
    for(propCounter = 1; propCounter <= 7; propCounter++) {
        // return value if m1, m2 and so on exists
        if(obj.timeline["m" + propCounter]) {
            return {key: "m" + propCounter, value: obj.timeline["m" + propCounter]};
        }
    }
};
  
// Loop over content array (assuming it contains objects)
for(i=0;i< content.length;i++) {
  current = content[i];
  firstMileStone = getMileStone(current); 
  result.push({
    'start': new Date(current.epc || firstMileStone.value),
    'end': new Date(current.m1 || firstMileStone.value),
    'content': firstMileStone.key,
    'group' : current.name,
    'classname' : firstMileStone.value
 });
}

UPDATE: The getMileStone function is simply a helper-function that can be called with any parameter. For example, you can call it with current[i+1]:

secondMileStone = getMileStone(current[i + 1]) 

Just make sure to check if you are not already at the last element of your array. If current[i+1] is undefined, then the helper function should also return undefined.

You can fallback to using the firstMileStone in that case:

secondMileStone = getMileStone(current[i + 1]) || firstMileStone;

View the updated fiddle (with additional check in the getMileStone helper function): http://jsfiddle.net/K37Fa/6/

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

Using Python to extract and process JSON data from a specific portion of a line within

Seeking assistance with parsing JSON data from a file. Each line in the file follows this format: some hexadecimal numbers|something else|int|UA info|{'computer': {'os': {'version': 'blabla', 'name': &apos ...

What is the correct way to update an empty object within the state using setState?

I'm currently dealing with a state that looks like this: this.state={ angles:{} } I need to know how to use setState on this empty object. Specifically, if I want to add a key and value inside my empty 'angles'. How can I achieve that? Fo ...

Connect the parent object's `this` to the child object's `this` in JavaScript

Exploring the world of object-oriented programming in JavaScript for the first time. It may sound like a simple question, but I really want to grasp this concept fully. var objA = { a : 10, b : 20, newobjB : { c : 100, funOfObjB: function(){ co ...

Error message: "Uncaught TypeError: Cannot set property 'state' of undefined in ReactJS"

I am encountering an issue while trying to update the state within my React function. The error message I receive indicates: "Cannot read property 'setState' of undefined." Reviewed below is my code where I have initialized the state in the cons ...

JavaScript - Populating Dropdown Menu with Fresh Information

I'm attempting to populate a combobox (input) with data fetched via AJAX. The goal is to display every city associated with a selected state, chosen from another select control (the state control). My Attempt: I've implemented the "change" even ...

Create a div element within the parent window of the iFrame

I'm trying to figure out how I can click a button within an iFrame that contains the following code: <td class="id-center"> <div class="bs-example"> <a id="comments" href="comments.php?id=$id" name="commen ...

Is it possible to create a single button that, upon clicking, fades in one image while simultaneously fading out another?

My goal is to have the blue square fade in on the first button click, then fade out while the red square fades in on the second click. Unfortunately, it seems that my current code is not achieving this effect. I'm open to any suggestions or help on h ...

Promise of a repeating sequence of serial calls

I am looking to create a recursive serial call to the promise method times, which will return the result of calling the fn function N times and storing the results in an array. To achieve this, I have added a new attribute called results to the times func ...

Remove a child node from its parent node in real-time

Currently, I am working on a project that involves adding and removing items as needed. The user interface can be seen in the image provided below: https://i.sstatic.net/Qhy2t.png Workflow: When the add icon is clicked, a new column is added for assignme ...

JavaScript never forgets to validate the user input

Forgive me for my lack of experience, but I am new to this and seeking guidance. I am struggling to find a straightforward example on how to validate HTML input using JavaScript. Currently, I am working on a search function and need help in implementing ...

modify header when button is clicked

I am trying to create a JavaScript function that will update the name of an HTML table header when a button is clicked. However, I am having trouble accessing the text content within the th element. document.getElementById("id").text and document.getEl ...

Smooth-scroll plugin does not activate active state (due to JS modification)

I'm currently facing an issue with a script that handles smooth scrolling and the active state on my main navigation. The plugin in question can be found at: It's important to note that the navigation bar is fixed and therefore has no height. T ...

Utilizing mixins with async components in VueJS

Currently, I am utilizing Webpack 2 to import components using a special syntax with require. Among the over 100 components available, only around 5-10 are used at any given time. These components share some common functionality such as props and lifecycl ...

"Utilize Vue i18n to properly display currency amounts in USD

Whenever I present my currency as USD, it always shows up like this: USD$500.00. I am attempting to eliminate the USD prefix from the beginning. Below is my numberFormats configuration: numberFormats: { 'en': { currency: { ...

Run some code and then enter interactive mode

Is there a method to run certain code (from a file or a string) before entering interactive mode in node.js? For instance, if I have script called __preamble__.js with the following content: console.log("preamble executed! poor guy!"); and a user enters ...

Getting the iframe onload event in an ASP.NET application

I have integrated ReportViewer to display SSRS reports on my .aspx page. However, since the ReportViewer is rendered as an iframe in the browser, I am looking for a way to trigger a JavaScript function every time the iframe loads. Using window.onload w ...

Executing JavaScript in Selenium is a common task that can be accomplished by

Attempting to automate a process using Python and Selenium has been successful for me on various websites in the past. However, I am currently facing a challenge with executing JavaScript on a specific site despite finding tutorials online. https://i.ssta ...

Utilizing AJAX to dynamically update a div's content by extracting a specific div from the retrieved data

Although I believe my code is correct, I am not very familiar with AJAX and have been struggling for hours to get it right. I've tried various approaches, including using filters, but nothing seems to work. The issue I'm facing is that the chat m ...

What is the best way to combine a hyperlink with a string in an Angular form?

Currently I am in the process of learning angular and experimenting with creating a list of websites that can be clicked on, similar to what you would find in a bookmark app. This is based on a todo example. https://github.com/LightYear9/ToDoList In orde ...

Is there a way to retrieve the disabled drop-down field value after submitting the form?

I'm struggling with a dropdown field that becomes disabled once an item is selected. After submitting the form, the dropdown field loses its value and I'm left with an empty field. Any suggestions on how to keep a value in the dropdown after subm ...