Discover the best approach for transforming a complicated JSON object/array into a map using inheritance coding techniques

Could someone help me with creating an array of objects (only 1 level) based on the following JSON structure?

[
    {
        'family' : {
            'name' : 'Doe',
            'from' : 'Foo'
        },
        'couples' : [
            {
                'couple' : {
                    'man' : 'Joe',
                    'woman' : 'Jane'
                },
                'childrens' : [
                    {
                        'name' : 'Joseph',
                        'sex' : 'male'
                    },
                    {
                        'name' : 'Martin',
                        'sex' : 'male'
                    }
                ]
            },
            {
                'couple' : {
                    'man' : 'Richard',
                    'woman' : 'Rose'
                },
                'childrens' : [
                    {
                        'name' : 'Rose',
                        'sex' : 'female'
                    },
                    {
                        'name' : 'Joe',
                        'sex' : 'male'
                    }
                ]
            }
        ]
    }
]

I want to consolidate all the children in one array (in this case, 4 elements) and update each element's __proto__ to include references to their parent elements (the children will have a reference to the couple, and the couple will have a reference to the family). This way, accessing the parents becomes easier.

I've come up with the following solution:

var childrenArr = [];
for (var i = 0; i < json.length; i++) {
    var family = json[i].family;
    var couples = json[i].couples;

    for (var j = 0; j < couples.length; j++) {
        var couple = couples[j].couple;

        var childrens = couples[j].childrens;
        for (var y = 0; y < childrens.length; y++) {
            var children = childrens[y];
            children.__proto__ = { couple : couple, family : family};

            childrenArr.push(children);
        } 
    }
}

However, I'm not entirely convinced that this is the optimal solution. Does anyone have suggestions on how I could improve this without using a framework?

Thank you!

EDIT

Below is an example using the code provided above.

var json = [
    {
        'family' : {
            'name' : 'Doe',
            'from' : 'Foo'
        },
        'couples' : [
            {
                'couple' : {
                    'man' : 'Joe',
                    'woman' : 'Jane'
                },
                'childrens' : [
                    {
                        'name' : 'Joseph',
                        'sex' : 'male'
                    },
                    {
                        'name' : 'Martin',
                        'sex' : 'male'
                    }
                ]
            },
            {
                'couple' : {
                    'man' : 'Richard',
                    'woman' : 'Rose'
                },
                'childrens' : [
                    {
                        'name' : 'Rose',
                        'sex' : 'female'
                    },
                    {
                        'name' : 'Joe',
                        'sex' : 'male'
                    }
                ]
            }
        ]
    }
]

var childrenArr = [];
for (var i = 0; i < json.length; i++) {
    var family = json[i].family;
    var couples = json[i].couples;

    for (var j = 0; j < couples.length; j++) {
        var couple = couples[j].couple;

        var childrens = couples[j].childrens;
        for (var y = 0; y < childrens.length; y++) {
            var children = childrens[y];
            children.__proto__ = { couple : couple, family : family};

            childrenArr.push(children);
        } 
    }
}

console.log(childrenArr);

// Example of accessing family attributes or couple attributes
console.log(childrenArr[0].family.name);

P.S.: in the example above, you can access childrenArr[0].family.name

Answer №1

An alternative method would be to use a nested approach in order to retrieve all children using Array#reduce.

var data = [{ family: { name: 'Smith', from: 'Bar' }, couples: [{ couple: { man: 'John', woman: 'Jill' }, children: [{ name: 'Johnny', sex: 'male' }, { name: 'Mandy', sex: 'female' }] }, { couple: { man: 'Robert', woman: 'Rachel' }, children: [{ name: 'Emily', sex: 'female' }, { name: 'Jack', sex: 'male' }] }] }],
    children = data.reduce(function (r, a) {
        return r.concat(a.couples.reduce(function (s, b) {
            return s.concat(b.children);
        }, r));
    }, []);

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

Adjustments made with the couple property.

var data = [{ family: { name: 'Smith', from: 'Bar' }, couples: [{ couple: { man: 'John', woman: 'Jill' }, children: [{ name: 'Johnny', sex: 'male' }, { name: 'Mandy', sex: 'female' }] }, { couple: { man: 'Robert', woman: 'Rachel' }, children: [{ name: 'Emily', sex: 'male' }, { name: 'Sarah', sex: 'female' }] }] }],
    children = data.reduce(function (r, a) {
        return r.concat(a.couples.reduce(function (s, b) {
            return s.concat(b.children.map(function (c) {
                return Object.assign({ couple: b.couple }, c);
            }));
        }, r));
    }, []);

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

Answer №2

const offspring = family_json[0].couples.map(function(pair){
    return pair.childrens;
});

This mapping function specifically extracts the children from the JSON data set.

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

Is it possible to link fields with varying titles in NestJS?

Currently, I am developing a NestJS application that interacts with SAP (among other external applications). Unfortunately, SAP has very specific field name requirements. In some instances, I need to send over 70 fields with names that adhere to SAP's ...

What sets Protractor apart from Grunt?

According to the Protractor website (http://www.protractortest.org/#/infrastructure), Protractor utilizes Selenium for browser automation. However, when browsing through the Grunt website (http://gruntjs.com/), it's mentioned that Grunt is also used f ...

What is the accurate way to determine the total number of minutes elapsed from a specific point in time?

String representation of the process start date: '2020-03-02 06:49:05' Process completion date: '2020-03-02 07:05:02' Question: What is the optimal method for calculating the time difference (in minutes) between the start and end ...

What is the best way to import the axios post method from a JavaScript file into a Vue component

I'm encountering an issue when trying to export the data received from the API in my JavaScript file and display it in my Vue file. Currently, I am sending a security JSON to the server using the POST method. Although I am able to retrieve the output ...

Tips for looping through each cell in a column of a DataTable to verify its content

I have a table generated using the jquery DataTables API. One of the columns displays word frequencies for each word in the table. If a frequency is less than 40, I want to change that cell to display "unranked" instead of the actual number. How can I ite ...

A step-by-step guide on accessing an expressjs endpoint from a static html file using Vercel

I am working on a basic app that consists of one server named /api/index.js and one file called index.html located at the root. In the index.js file, there is a route defined as app.get("/api/mystuff", () => {...}) The index.html file makes a request ...

Saving form blueprints and operations in a Data Repository

My team and I are working on a sophisticated web application with a complex back end. We have hundreds of form schemas paired with their corresponding return functions, which are triggered upon form submission. These JSON objects dynamically generate forms ...

Unable to iterate through elements of a string array using PowerShell

Having trouble looping through items using PowerShell with the code below. $ipAddress = @('107.20.253.26', '107.20.178.220', '8.8.8.8') for($i=0; $i -le $ipAddress.count; $i++) { $resolve = nslookup $i | Format-list ...

The GET request on the Express route is malfunctioning, causing the Postman request to time out after getting stuck for some

My Express app seems to be experiencing some issues with the GET route. When making a request using Postman, the response gets stuck for a while before fetching. The GET route is properly set up with all necessary request parsers and the app initialized an ...

Navigating to a Different Page in React Based on Button Click and Meeting Specific Conditions

Within this particular component, I have implemented a button named Submit. When this button is clicked, it triggers a series of actions: first, it exports the drawing created by the user as a jpeg URL, then sends this image data to another API that genera ...

In the world of programming, there exists a mysterious creature known as

I've been experimenting with different methods, but nothing seems to be working for me. What I am attempting to accomplish is <?php $php_var = a-thing; echo ' <script text/JavaScript> document.cookie = "arrayid"+&apos ...

Generating interactive elements in VUE is key

I am unsure about how to dynamically create components without using the <component :is=''> tag. I would like to insert a component into the DOM through JavaScript. Similar to how you would add a new modal in jQuery with $("body").append(" ...

Is real-time updating possible with data binding in Polymer and JavaScript?

I have a scenario where I am working with two pages: my-view1 and my-view2. On my-view1, there are two buttons that manipulate data stored in LocalStorage. On my-view2, there are two simple div elements that display the total value and the total value in t ...

The jQuery.ajax request encounters issues within a Chrome extension

I'm in the process of migrating one of my Firefox browser extensions to Chrome, and I've encountered an issue related to an AJAX query. The code snippet provided functions correctly in the Firefox extension but fails with a status of "0" when exe ...

Learn how to utilize the combineLatest/zip operators to only respond to emissions from the second observable while disregarding emissions from the first observable

Here's an example of how I'm initializing a property: this.currentMapObject$ = zip(this.mapObjects$, this.currentMapObjectsIndex$, (mapObjects, index) => mapObjects[index]); I want the value of this.currentMapObject$ to be emitted only ...

Determine the return type of a function based on a key parameter in an interface

Here is an example of a specific interface: interface Elements { divContainer: HTMLDivElement; inputUpload: HTMLInputElement; } My goal is to create a function that can retrieve elements based on their names: getElement(name: keyof Elements): Elemen ...

Troubleshooting a problem with Angular routing when trying to access a specific URL using

My main objective is to enable users to view products by clicking on the item itself. For each product item displayed in main.html, the URL format is like this... <a href="/products/{{ product.id }}">{{ product.title }}</a> For instance, when ...

A guide on adding a personal library to Ember using npm

Despite the abundance of blog posts discussing it, I am still facing challenges in utilizing a custom library as a dependency for my ember application through npm. I have developed a WebGL library and successfully imported it into my Ember app by installi ...

Executing a function on each page within the head tag in Nuxt.js

I successfully made my function accessible by using the plugin attribute in the nuxt.config.js file, allowing me to call the function under mounted on every page. I am looking for a more efficient way to run this function within the head tag and have it b ...

Stop and start an Express.js server using the original port number

Currently, my Node.js application utilizes Express.js to handle incoming connections. The code snippet looks something like this: const express = require("express"); var server = express(); server.get("/test", (req, res) => testResponse(req, res)); ser ...