Gather a linear array of deeply nested information

Below is a dictionary:

var objectSchemasList = {
  1: [
    {
        name: 'list_field1_1',
      uuid: 'uuid1',
      fieldObjectSchemaId: 2
    },
    {
        name: 'list_field1_2',
      uuid: 'uuid2',
      fieldObjectSchemaId: null
    },
  ],
  2: [
    {
        name: 'list_field2_1',
      uuid: 'uuid3',
      fieldObjectSchemaId: null
    },
    {
        name: 'list_field2_2',
      uuid: 'uuid4',
      fieldObjectSchemaId: null
    },
  ],
  3: [
    {
        name: 'list_field3_1',
      uuid: 'uuid5',
      fieldObjectSchemaId: 1
    },
    {
        name: 'list_field3_2',
      uuid: 'uuid6',
      fieldObjectSchemaId: null
    },
  ],
}

Here is an array of related data:

const objectSchemaFields = [
    {
    name: 'field_1',
    uuid: '_uuid1',
    fieldObjectSchemaId: null
  },
  {
    name: 'field_2',
    uuid: '_uuid2',
    fieldObjectSchemaId: null
  },
  {
    name: 'field_3',
    uuid: '_uuid3',
    fieldObjectSchemaId: 1
  },
];

This structure allows nested fields within objects, linked by the fieldObjectSchemaId. For instance, objectSchemaFields[2] element corresponds to

objectSchemasList[objectSchemaFields[2].fieldObjectSchemaId]
, which in turn refers to objectSchemasList[2] and so forth. The nesting can be infinite. The objective is to obtain a flat array from this setup. You can view my attempt here. The final array should be flattened and include only the properties path, name, uuid. Each path comprises the parent name concatenated with all child names separated by periods. An example result would look like:

const result = [
  {
    path: 'field_1',
    name: 'field_1',
    uuid: '_uuid1',
    },
  {
    path: 'field_2',
        name: 'field_2',
    uuid: '_uuid2',
    },
  {
    path: 'field_3',
    name: 'field_3',
    uuid: '_uuid3',
  },
  {
    path: 'field_3.list_field1_1',
    name: 'list_field1_1',
    uuid: 'uuid1',
  },
  {
    path: 'field_3.list_field1_1.list_field2_1',
    name: 'list_field2_1',
    uuid: 'uuid3',
  },
  {
    path: 'field_3.list_field1_1.list_field2_2',
    name: 'list_field2_2',
    uuid: 'uuid4',
  },
  {
    path: 'field_3.list_field1_2',
    name: 'list_field1_2',
    uuid: 'uuid2',
    }
]

Answer №1

Utilizing the map function may not be ideal in this scenario, as it requires returning both the original object and its child objects while also needing to flatten them afterwards. It might be more efficient to stick with a traditional array variable or consider using the reduce method for a more sophisticated approach.

var output = [];

function processObject(path, obj) {
  path = path.concat([obj.name]);
  output.push({
    path: path.join("."),
    name: obj.name,
    uuid: obj.uuid,
  });
  var schema = objectSchemasList[obj.fieldObjectSchemaId];
  if (schema) {
    schema.forEach(processObject.bind(null, path));
  }
}

objectSchemaFields.forEach(processObject.bind(null, []));

https://jsfiddle.net/m8t54bv5/

Answer №2

One approach is to condense the arrays by implementing a recursive flattening function.

function flatten(parentPath) {
    return function (resultArray, { name, uuid, fieldObjectSchemaId }) {
        var path = parentPath + (parentPath ? '.' : '') + name;
        resultArray.push({ path, name, uuid });
        return (objectSchemasList[fieldObjectSchemaId] || []).reduce(flatten(path), resultArray);
    };
}

var objectSchemasList = { 1: [{ name: 'list_field1_1', uuid: 'uuid1', fieldObjectSchemaId: 2 }, { name: 'list_field1_2', uuid: 'uuid2', fieldObjectSchemaId: null }], 2: [{ name: 'list_field2_1', uuid: 'uuid3', fieldObjectSchemaId: null }, { name: 'list_field2_2', uuid: 'uuid4', fieldObjectSchemaId: null }], 3: [{ name: 'list_field3_1', uuid: 'uuid5', fieldObjectSchemaId: 1 }, { name: 'list_field3_2', uuid: 'uuid6', fieldObjectSchemaId: null }] },
    objectSchemaFields = [{ name: 'field_1', uuid: '_uuid1', fieldObjectSchemaId: null }, { name: 'field_2', uuid: '_uuid2', fieldObjectSchemaId: null }, { name: 'field_3', uuid: '_uuid3', fieldObjectSchemaId: 1 }],

result = objectSchemaFields.reduce(flatten(''), []);

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

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

Avoiding the <br> tag in list items with TinyMCE

I am currently using tinyMCE and I needed to enable the "force_br_newlines: true" option. Without this setting, if I press the "Enter" key twice and check the source code, I only see one <br> tag. However, when I set the option to TRUE, it creates a ...

Encountering a Sass Dart error "Bad state: Can't access parent outside of a module" while running npm start in a Create React App

My team has come across an unusual error while attempting to npm start a Create React App we are working on. The error message states: Bad state: Can't access __parent outside of a module, resulting in a failed Build process. This issue is new to us, ...

When using the JavaScript Fetch API to send multipart form data, FastAPI responds with "Error 422: Unprocessable entity"

I'm facing an issue with using the Fetch API JavaScript method to send simple formData as shown below: function register() { var formData = new FormData(); var textInputName = document.getElementById('textInputName'); var sexButtonActi ...

Bringing in a variable from a React component to a JavaScript file

I've created a React component called Button with two states named name and players. Now, I need to access these states in a separate JavaScript file that is not a component. Below are the relevant code snippets: Button.js import {useState} from &qu ...

Place the Drawer element at the bottom of the menu

Is there a way to position the menu point at the bottom of the screen? It would be great if we could easily customize the style of the navigation options for each element. Check out my App Navigator below: const AppNavigator = createDrawerNavigator( ...

Update current properties of objects

I'm feeling like I'm going crazy and could really use some assistance. My predicament involves a function that looks like this: private generateTimeObject(firstObject: someInterface, secondObject?: someInterface) { let firstTime; let secondTi ...

What is the best method for displaying a table using a JSON array?

I have a JSON array that I want to display in a table using React boxes: [ { id: 1, color: "red", size: "small" }, { id: 2, color: "blue", size: "medium" }, { id: 3, color: "green", size: "large" }, { id: 4, color: "yellow" ...

Passing an array by reference in C++: Step-by-step guide

I have been perfecting my skills in C++ and this is the code I've been working on. Could someone help me figure out how to modify ArraySortToMedian() so that it uses pointer notation instead of array notation to handle the array? Despite several atte ...

What is the best method in JavaScript to create three different shades of a color?

My sass function generates lighter and darker versions of a base color, here is the code snippet: $colors: ( betpawa-green: #107A3D, lime-green: #8DC63F, yellow: #FBCD00, ); @mixin color-generator { @each $name, $hex in $colors { &-#{$nam ...

Why isn't it possible to send POST data to a JSON file using JQuery/AJAX?

I'm currently learning how to use JQuery/Ajax from a helpful tutorial on YouTube. To watch the video, simply click here. While I can successfully retrieve data from the order.json file, I encounter an error whenever trying to send POST requests. Bel ...

What is the best way to access and iterate through JSON data?

I am trying to extract data from my Json file, however, I cannot use a specific 'key' because it changes on a daily basis. https://i.sstatic.net/sZySk.png My attempted solution is as follows: template: function(params) { const objects ...

Cease the use of bi-directional data binding on an Angular directive

One way I've been attempting to send information to a directive is through the following setup: <ui-message data="{{app}}"></ui-message> In my controller, this is how I define it: app.controller("testCtrl", function($scope) { $scope.a ...

What is the best way to deliver client/index.html using server/app.js?

Here is my current file structure: - simulated-selves - client - index.html - server - app.js The goal is to serve the user index.html when they visit the / route. // server/app.js app.get('/', function(req, res) { res.sendFile( ...

Translate CSS into JavaScript while maintaining selector understanding

I am interested in developing a tool that can read a .css file and generate a function that will accept an array of class names as input and output the corresponding styles for an element with those classes, represented as a JavaScript object. This tool wo ...

Error encountered: 'applePaySession.completeMerchantValidation' is not a valid object reference when attempting to process a successful apple pay payment

So, I'm having an issue with the user's payment going through but encountering undefined value when checking compatibility. I've been trying to debug this problem in my code snippet below: setCanDisplayApplePay() { var client = n ...

What steps need to be taken to utilize the fast-json package within a web browser environment?

In my quest to enhance the performance of my apps, I stumbled upon two intriguing packages. Currently, I am working on a forum-style app that constantly receives and processes information from APIs. Despite optimizing my frontend JavaScript to the best of ...

Performing an AJAX request from a subfolder

Can anyone help me figure out how to make an ajax request from a page located in a subdirectory and receive a response? On my webpage, index.jsp is situated within a subdirectory called /vf2. In this page, there is a script file included: <script src=" ...

Investigate duplicate elements within nested arrays using the 3D array concept

I am dealing with an array that contains 3 subarrays. Arr = [[arr1],[arr2],[arr3]] My task is to identify and store the duplicate values found in these subarrays ([arr1],[arr2],[arr3]) into a separate array. Arr2 = [ Duplicate values of arr 1,2,,3 ] What ...

Filter out all elements in an array except for one from a JSON response using Angular 2

After receiving a JSON response from a server via HTTP GET, the data structure looks like this: { searchType: "search_1", overview: [ "Bed", "BedSheets", "BedLinen", .. ...

It seems that the JavaScript object is producing varied values in distinct locations despite no alterations made in between

I've encountered a puzzling issue where a variable is returning different values within a function, despite no modifications being made to it. This problem arises in a form component created using Vue.js (v2) that triggers a Vuex action. While I beli ...