Developing a structured array of JSON objects

As I reach the final stages of completing my JavaScript code for generating an array of JSON formatted objects, I have successfully created a top-level parent along with its corresponding child records.

Now, my task is to add more records to one or more child records. This is where I am encountering some difficulties.

The target data includes a top-level node with "id": 29 and a "children" array beneath it:

 [
  {
    "id": 29,
    "field0": "$ALL$",
    "field1": 1564.92711931719,
    "field2": -171.934775655824,
    "field3": -292.877167373888,
    "children": [
        // Child records here
    ]
  }
 ]

Next, I have a remaining source array that needs to be linked to its respective parent record mentioned above.

[   
{
    // Source array items here
}

Using UnderscoreJS library, I can locate each item in the remaining source array, but I need help on how to append them to the parents[] array.

In an update, I have included an _.each() loop which is starting to create the children records; however, there are still some items left in the source array that will eventually become part of the nested hierarchy.

findPar["children"] = thisChild[0]; 

I believe there could be a more efficient way to achieve this goal.

       var findPar;
        _.each(rowsNew, function (row) {
              // Locate parents array based on id == row.parent condition
            findPar = _.findWhere(parents[0].children, { id: row.parent }); 
            if (findPar != undefined) {                          
                if (findPar.children == undefined) {
                    findPar["children"] = createJsonFromSingleRow(row);
                }
                else {
                    findPar.children.push(createJsonFields(row));
                }
                rowsNew = _.reject(rowsNew, function (rec) { return rec.id == row.id;  });                }
        });
        return newJson = parents;

Thank you for your assistance.

Sincerely, Bob

Answer №1

To simplify the process, consider using objects with unique identifiers instead of arrays in your code. You could create a function to convert raw JSON objects accordingly.

var hash = {
  '29' : {
    "id": 29,
    "field0": "$ALL$",
    "field1": 1564.92711931719,
    "field2": -171.934775655824,
    "field3": -292.877167373888,
    "children": {
        '0': {
            "id": 0,
            "field0": "Goldman",
            "field1": 0,
            "field2": 0,
            "field3": 0
        },
        '1': {
            "id": 1,
            "field0": "IBM",
            "field1": 0,
            "field2": 0,
            "field3": 0
        },
        ...
        '35': {
            "id": 35,
            "field0": "PIMCO",
            "field1": 0,
            "field2": 0,
            "field3": 0
        }
    }
  }
 };

To incorporate any leftover items into the parent hash using plain JavaScript, assuming you have already structured the leftovers similarly:

for( key in leftovers ){
  if( leftovers.hasOwnProperty(key) ){
    var parent = leftovers[key].parent;

    // Create parent if doesn't exist in the hash
    if( !parent in hash ) {
      hash[parent] = { 
        id: parent,
        children: {}
      };
    }

    // Ensure children object exists within the parent node
    if( !hash[parent].children ) {
      hash[parent].children = {};
    }

    // Copy the object from leftovers to parent hash (using copyObj)
    hash[parent].children[key] = copyObj(leftovers[key]);  

    // Remove item from leftovers once added to parent
    delete leftovers[key];
  }
}

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

Connect to the Kendo dropdown list undefined

I am looking to automatically bind a model to a Kendo dropdown list. The model is retrieved from the server and can sometimes be undefined or a valid object. My problem arises when the value is undefined. In this case, Kendo selects the first item in the ...

"Encountered an issue with combining multiple meshes that share the same geometry but have

I wrote a loop that generates multiple Mesh objects with various geometries, where each mesh corresponds to a specific texture: var geoCube = new THREE.CubeGeometry(voxelSize, voxelSize, voxelSize); var geometry = new THREE.Geometry(); for( var i = 0; i ...

Creating a Vue Directive in the form of an ES6 class: A step-by-step

Is it possible to make a Vue directive as an ES6 Class? I have been attempting to do so, but it doesn't seem to be working correctly. Here is my code snippet: import { DirectiveOptions } from 'vue'; interface WfmCarriageDirectiveModel { ...

Chrome extension causing delays in rendering HTML on webpage

Currently, I am developing a script (extension) that targets a specific HTML tag and performs certain actions on it. The challenge I am facing is that this particular HTML tag gets dynamically loaded onto the page at a certain point in time, and I need to ...

The ng-model in AngularJS is experiencing issues with two-way binding within a directive

Seeking to develop a straightforward Angular directive for handling currency input. The objective is to have it operate as a float in the model while showing two decimal places to the user. The code implemented for this purpose is as follows: // Currenc ...

How about utilizing node.js as a peer for WebRTC?

Are there any available modules for utilizing node.js as a peer in WebRTC? I am interested in using WebRTC in a client/server manner rather than P2P for its ability to send packets unreliably (i.e. avoiding the delay caused by TCP's guarantee of packe ...

Retrieve key codes from inputs sharing the same class

My webpage contains multiple text inputs that all share the same class for various reasons. Currently, I am attempting to capture the ESC button press when an input is focused and alert whether the input has a value or not. However, this functionality on ...

Having trouble finding the maximum and minimum dates with Moment()?

My task involves working with an array of dates and finding the maximum and minimum dates within it. Below is the code I've written for this purpose: let date_list = [ "2021-03-19T00:00:00Z", "2021-03-20T00:00:00Z", "2021-04-12T00:00:00Z", "202 ...

Issues regarding the Weather API provided by APIXU

As a beginner in API requests, I am currently working on displaying the current weather in Toronto by making APIXU API calls. Despite referring to the documentation at , I seem to be encountering some issues with my implementation. Below is the HTML code ...

What is the best way to add items with an index to a Vue Js 2 object?

Greetings! I'm struggling with adding items to an object with specific indexes. I have an empty object defined like this: let data {}; The desired structure for the data object is: // expected array data = { 1000: ['a', 'b'], ...

Extracting Data from JSON

My task involves making a GET request and then parsing the JSON response body to extract specific values from it. Specifically, I am focusing on retrieving the subject field of a helpdesk ticket in this example. While I can successfully obtain the response ...

What is the best way to prevent the use of ctrl key in multiple select feature of vue.js

Recently, I decided to create a custom multiselect feature without using any pre-made packages. However, I found it frustrating that in order to select multiple elements, I had to use the ctrl key. This functionality was not user-friendly, and I wanted t ...

Generating masks of different lengths using tensorflow

I'm trying to manipulate a tensor of lengths in TensorFlow, which looks like this: [4, 3, 5, 2] My goal is to generate a mask consisting of 1s and 0s, where the number of 1s corresponds to the values in this tensor, padded with 0s to a total length ...

Compare the PHP Array data and determine any discrepancies in the match. Display the items that do

I am currently working on some PHP code that involves selecting data from two different databases and creating arrays with the information. $sql="SELECT * from voip_emergency_services_data "; $rs=mysql_query($sql,$conn) or die(mysql_error()); if(mysql_num ...

JavaScript: create a button that dynamically changes size and color when scrolling

I have a pulsing button (#scrollarrow) at the bottom of my website that disappears as I start scrolling. The jQuery code responsible for this effect is as follows: $(document).ready(function(){ $(window).scroll(function(){ if ($(thi ...

Developing a variety of jQuery tabs

I am encountering an issue with my ASP.NET MVC page where dynamically created divs within a jQuery tab are not displaying subtabs as expected. Although the parent tabs are rendering correctly, the subtabs are not being created for some reason. The Razor ...

Looking for arrays with duplicate values across multiple elements - a comprehensive guide

I need assistance with a PHP script that retrieves arrays where the values of specific fields are identical. Below is the code I have so far, but as I am new to PHP development, any guidance would be appreciated. Code: foreach($leads_details->resul ...

Having trouble fetching JSON data with PHP when the query contains spaces

My Objective I'm working on utilizing the RottenTomatoes API to gather data about a specific movie. For instance, when I search for Frozen, this is the script I use: $q = 'Frozen'; $json_link = 'http://api.rottentomatoes.com/api/pub ...

What could be causing me to receive an outdated useRef() value?

After creating a hook with the purpose of adding cherries to an array, I encountered an issue: import { useReducer, useRef } from "react"; const useCherry = () => { const myRef = useRef(0); const [state, dispatch] = useReducer( ...

Tips for auto-saving data in Laravel with AJAX after a few seconds?

I've set up the article post section in my project. I want to automatically save data as a draft in my articles table when creating a new post. I have included the blade file with a form and ajax code, but the ajax code doesn't seem to be working ...