Establishing the properties of an object as it is being structured within a nested data format

I am in the process of creating a unique JSON representation, focusing on object composition to directly set key values during composition. However, I've encountered difficulty composing multiple objects in a nested manner.

My goal is to find an expressive method for constructing object data structures with reusable components in a concise way, acting as a substitute for JSX. Therefore, I'm looking to "reuse" these object components and assign children keys using equal signs during composition. I aim to stick to pure native JavaScript without any external libraries. My assumption about JSX is that it likely converts HTML tags from strings using regular expressions? Ideally, I would like to use object literals for my solution. Any insights are welcome.

For instance:

const foo = {
    name: 'Bob',
    abilities: {
        superpower: 'Says grrr',
        mood: 'Gruchy'
    }
}

const bar = {
    name: 'Denny',
    abilities: {
        superpower: 'Diabetes',
        mood: 'Hopeful'
    }
}

const dataStructure = {
    name: 'something',
    children: [
        foo.children = [ // 'foo' object will result in an array, even if we only set .children
            bar.children = [
                {
                    name: 'somethingElse'
                }
            ]
        ]
    ]
}

/*
    Desired resulting data structure:

    {
        name: 'something',
        children: [
            {
                name: 'Bob',
                abilities: {
                    superpower: 'Says grrr',
                    mood: 'Gruchy'
                },
                children = [
                    {
                        name: 'Denny',
                        abilities: {
                            superpower: 'Diabetes',
                            mood: 'Hopeful'
                        },
                        children = [
                            {
                                name: 'somethingElse'
                            }
                        ]
                    }
                ]
            }
        ]
    }
*/

Answer №1

Below is an illustration of a functioning example:

const person1 = {
  name: 'Alice',
  traits: {
    superpower: 'Telekinesis',
    mood: 'Calm'
  }
}

const person2 = {
  name: 'Eve',
  traits: {
    superpower: 'Invisibility',
    mood: 'Mischievous'
  }
}

const data = {
  title: 'something',
  group: [{
    ...person1,
    accomplices: person1.accomplices = [{
      ...person2,
      companions: person2.companions = [{
        name: 'anotherThing'
      }]
    }]
  }]
}

console.log('Data:', data)
console.log('Person1:', person1)
console.log('Person2:', person2)

Note: However, the approach you are taking seems quite unconventional...

Answer №2

It is important to place your bar.children outside of the variable definition to prevent it from being called again unnecessarily. In the code snippet below:

bar.children = 
{
    name: 'somethingElse'
}

const dataStructure = {
    name: 'something',
    children: 
        [foo,
        children = [bar]]
}

You will see the following output:

{
    "name": "something",
    "children": [
        {
            "name": "Bob",
            "abilities": {
                "superpower": "Says grrr",
                "mood": "Gruchy"
            }
        },
        [
            {
                "name": "Denny",
                "abilities": {
                    "superpower": "Diabetes",
                    "mood": "Hopeful"
                },
                "children": {
                    "name": "somethingElse"
                }
            }
        ]
    ]
}

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

Displaying Array Information in JavaScript

After spending a significant amount of time searching online, I have not been able to find a working solution to achieve what I need. Essentially, I am making an AJAX request that executes a database query and then outputs the results using echo json_enco ...

Examining the appearance of react-hot-toast using jest testing

As I work on my application, I am facing a challenge in writing a test for the appearance of a react-hot-toast. Whenever a specific button is clicked, this toast pops up on the screen and disappears after a brief moment. Despite being visible both on the s ...

Step-by-step guide to utilizing instance functions in AngularJS

Recently I started working with angular in my project but I'm struggling to figure out how to access instance functions from the original code. Here is a snippet of my function: $scope.collapsedrow = true; $scope.PlusClick = function(event) ...

The battle between Iteration and Recursion: Determining the position of a point in a sequence based

One of the challenges I'm facing involves a recursive function that takes a point labeled {x,y} and then calculates the next point in the sequence, recursively. The function in question has the following structure: var DECAY = 0.75; var LENGTH = 150 ...

Unexpected behavior observed in the Python minifier Slimit

Attempting to decrease the size of some JavaScript code using the 'slimit' package in Python. import slimit slimit.minify('[1,2,3,4,5,6,7,8]') The above snippet executes without issue and outputs '[1,2,3,4,5,6,7,8]' import ...

Implementing a dynamic function with jQuery Tokenize's change event

I'm currently facing an issue with triggering the on change event on the select box from jQuery Tokenize. Below is the code snippet I am working with: <select id="tokenize" multiple="multiple" class="tokenize-sample"> <option value="1"&g ...

Is it possible to set up a server with 'app' as the designated request handler?

When working with NodeJS, server creation can be done simply by using: http.createServer(function(req,res) { /* header etc. */}); However, as I delved into using express, the server was automatically created for me. Moving on to learning about sockets, I ...

Access a webpage whose URL has been dynamically assigned using JavaScript

I have a website that consists of a single page and features four tabs. Whenever a tab is clicked, it displays the corresponding content in a div while hiding the other three divs along with their respective content. To ensure a smooth user experience, I u ...

Mouseover function not triggering until clicked on in Google Chrome

I'm attempting to execute a function when the cursor hovers over a list item as shown below: <div id="vue-app"> <ul> <li v-for="item in items" @mouseover="removeItem(item)">{{item}}</li> </ul> </div> ...

Tips for creating CSS styles for a selected input field

I seem to be stuck in a situation where my screen looks similar to the screenshot provided. There are four input elements that I would like to have bordered just like in the image, complete with a circled tick mark. I've managed to create these four i ...

Streamlining programming by utilizing localStorage

Is there a more efficient way to streamline this process without hard-coding the entire structure? While attempting to store user inputs into localStorage with a for loop in my JavaScript, I encountered an error message: CreateEvent.js:72 Uncaught TypeErr ...

What strategies can be employed to mitigate the activation of the losing arm in a Promise.race?

My current task involves sending the same query to multiple identical endpoints (about five) across various Kubernetes clusters. The goal is to aggregate the results without any delays and report failures to the user while continuing with the process seaml ...

Stop automatic page refresh after submitting a jQuery post request

I've tried various solutions, but unfortunately, neither e.preventDefault() nor return false seem to be working for me. When I use prevent default ajax doesn't make post request. Even using $.post doesn't work as expected. Furthermore, addin ...

The drop-down list unexpectedly closes at the most inconvenient moment

I am looking to create a search input with a drop-down list. The requirement is for the list to close when the focus or click is anywhere except the search input. I have added a function listClose() to the "blur" listener, but now I am unable to capture t ...

The JavaScript function getSelection is malfunctioning, whereas getElementById is functioning perfectly

I am encountering a peculiar situation while trying to input text into a textbox using a JavaScript command. The CSS locator does not seem to update the text, whereas the ID locator is able to do so. URL: Below are screenshots of the browser console disp ...

Is there a way to extract information from my JSON file and display it on my website?

My aim is to populate my HTML page with data from a JSON file. Approach I created a JavaScript file: update-info.js In this file, I used an AJAX call to retrieve data from my JSON file data.json If the request is successful, I utilized jQuery's .htm ...

Troubleshooting: Mongoose Array Object Order Modification Issue

Imagine we have a person named Michael who lists his favoriteFruits as [ { name: 'Apple'}, {name: 'Banana'} ] The challenge at hand is to change the order of his favorite fruits. In other words, we want to transform it from: [ { name ...

Executing ESM-Enabled Script in Forever

Is it possible to execute a script using the option -r esm in Forever? When I try to run the configuration below, I encounter an error message that reads: Unexpected token import. Here is the configuration: { "uid": "app", "script": "index.js", "s ...

Error: An issue occurred in the driver.execute_script function causing a JavascriptException. The error message indicates

When attempting to run some JavaScript code on the Chrome driver, I encountered a JavascriptException. Despite my confidence in the correctness of the JS code, the following error message was displayed: raise exception_class(message, screen, stacktrace) s ...

Troubleshooting Issue with JQuery Date Picker: Date Not Valid

Encountering an issue when using the date from JQuery DatePicker in an SQL Statement variable, resulting in an error of invalid datetime string. Even after attempting to format it with DateTime.Parse or Convert.DateTime. JQuery DatePicker <script> ...