Reorganize array into nested structure using JavaScript

Here is the issue I'm facing along with a link to the code: https://jsfiddle.net/6zqco0mj/

const start = [{'a':'b'}, {'b':'c'}, {'c':'d'}, {'d':'e'}]
end = 
{a:
  {b:
    {c:
      {
       d: {}
      }
    }
  }
}

I have some code but I'm unsure of how to delve deeper into an object's structure

const start = [{'b':'c'}, {'a':'b'}, {'c':'d'}, {'d':'e'}];
const end = {};

function convert(key) {
  const obj = getObj(key);

  if(obj) {
    const temp = {};
    temp[obj[key]] = convert(obj[key]);
    //findKey(obj[key]);
    end[key] = temp;
  }
}

function getObj(key) {
  const foo = start.find((el, i) => { if(el[key]) { return el[key] } });
  return foo;
}

function findKey(k) {
// What should be inserted here?  
}
convert('a');
console.log(end);

Answer ā„–1

It seems like your approach to recursion might be a bit different than usual. I decided to give it a shot and explore this new way of thinking about it.

const start = [{'b':'c'}, {'a':'b'}, {'c':'d'}, {'d':'e'}];


function convertKeysToValues(key, object) {
   const obj = findObjectByKey(key);

 if(obj) {
   object[obj[key]] = {};
   convertKeysToValues(obj[key], object[obj[key]]);
 }
}

 function findObjectByKey(key) {
  const matchedObj = start.find((el) => { if(el[key]) { return el[key] }});
  return matchedObj;
}

const endResult = { a: {}};

convertKeysToValues('a', endResult.a);
 console.log(endResult);

Answer ā„–2

One approach is to use an object structure to gather the data and construct a tree from it.

This method is designed to handle unsorted data.

To extract the root properties, all keys and values are gathered and a subset is then selected.

var data = [{ d: 'e' }, { b: 'c' }, { c: 'd' }, { a: 'b' }, { b : 'z' }],
    tree = function (data) {
        var keys = new Set,
            values = new Set,
            r = Object.create(null);

        data.forEach(function (o) {
            var [key, value] = Object.entries(o)[0];
            keys.add(key);
            values.add(value);
            r[value] = r[value] || {};
            r[key] = r[key] || {};
            r[key][value] = r[key][value] || r[value];
        });

        values.forEach(v => keys.delete(v));
        return Object.assign(...Array.from(keys, k => ({ [k]: r[k] })));
    }(data);

console.log(tree);
.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

Rendering React.js components as children of DOM elements

Trying my hand at creating a custom Map component includes the task of designing a unique Map Annotation. Here's an example of how a MapAnnotation component appears in the render function: <MapAnnotation title='Annotation' latitude={ 12.3 ...

Breaking apart a string that consists of boolean values

Presented below is a JavaScript function function cmd_parse( cmd ) { return cmd.split( /\s+/ ); } For instance, when calling the function like this words = cmd_parse("hello jay true"); The output would be words[0]="hello" words[1]="jay" wor ...

Retrieve data from a database using a select query and store the results in a

I'm struggling to figure out how to approach this issue: I need to query my MySQL database in order to create a multidimensional associative array of selected tables. The desired structure of the array is as follows: $ar = Array( table1name=> ...

The success function in Ajax jQuery isn't being triggered even though the code is running

When using AJAX, I am trying to pass a json variable. Here is the ajax function I have: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script> function emailCheckForFrontend() { var key='7 ...

jQuery AJAX Loading Image Delays

Seeking assistance in implementing a loading gif for an ajax call on one of my pages. Utilizing jQuery's ajax method, my current code is as follows: $.ajax({ type:'POST', data:{action:'yadayada',data:stuffToSend}, cach ...

Acquiring an alternative data structure in JavaScript or JSON

When clicking on a div with different attributes, I am attempting to retrieve a data object. Here is an example: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> var locA = { "fro ...

unable to effectively test promises with stubs using nodejs mocha

Currently, I am facing a couple of challenges when attempting to perform unit testing on promises using Mocha. 1) The main issue I encounter is an Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Prom ...

Utilizing json_encode() while sending an array as an object

After sending an AJAX request with an ID, I am eagerly awaiting a response from PHP containing additional information. The response from PHP is structured like this: Array ( [success] => 1 [id] => 20 [fullname] => John Doe [status ...

Error retrieving data from the ngresource properties resource

In the code snippet below, I have a simple factory that requests a json object containing location information. The requests are successful and the data is present in the object. However, there seems to be a scope problem as I am unable to access the prope ...

Creating a regular expression variable in Mongoose: A step-by-step guide

I am looking for a solution to incorporate a variable pattern in mongoose: router.get('/search/:name', async(req, res) => { name = req.params.name; const products = await Product.find({ name: /.*name*/i }).limit(10); res.send(prod ...

The issue at hand is that the aggregation problem in MongoDB remains unsolvable

My goal is to identify books with at least two authors and no more than three authors, along with their ISBN, title, and publisher information. However, the structure of the BOOK collection in my database makes this task a bit complex for me to execute. ...

extracting values only when converting to JSON using the to_json method in Python with the orient set to "records"

Here is the initial output that I am working with: quarterly_churn_count["Churn"] Out[35]: year quarter 2008 1 1070 2013 1 31 2 47 3 57 4 59 2014 1 33 2 ...

Executing control with AngularJS when ng-change event occurs

When using AngularJS One interesting scenario I encountered is having a ng-change event on a text field and seeing the function being called correctly: <input type="text" ng-model="toggleState" ng-change="ToggleGroupVisiable()" data-rule"" /> The ...

Using the ternary operator in Array.map causes issues with Babel's react preset

Check out this code snippet that I'm having trouble with: someArray.map( condition ? element => ({ field: element.someField }) : element => ({ field: element.someOtherField }) Iā€™m currently using Webpack 2.3.3 ...

Python - Retrieving Numerous Elements in a List

Apologies for the lack of detailed information. Here is a snippet of code that I am referring to: import json import requests def funcname(): response = requests.get('https:aig.com/e/id') parsed_response = json.loads(response.text) p ...

Packages starting with @ are found in the Node.js ecosystem

What's the deal with libraries in Node.js starting with @ symbols? Is there a specific convention for this? I feel like I'm missing something obvious here. ...

Finding the current div based on the scrolling position can be achieved without the use of jQuery

Seeking assistance with a coding challenge. I have a solution in jQuery, but we require the solution in plain JavaScript or Angular. It seems like something is missing. Take a look at this fiddle. The objective is to highlight the corresponding left panel ...

Is there a way for me to display a new object from form2 when I click on the button object? (C#-Windows form application)

public void handleClickEvent(object sender, EventArgs e) { for (int i = 0; i < 1; i++) { GunaButton btn = new GunaButton(); //add btn to flowlayoutpanel to arrange buttons flowLayoutPanel1.Controls.Add ...

Storing a multiline HTML-encoded text within an SQL database

How can I effectively store HTML code in an SQL database after encoding it with encodeURI()? Unfortunately, I am encountering multiple errors while attempting to do so. https://i.sstatic.net/QKNYt.png I have tried using dataType as <CLOB> and also ...

Is there a way to verify within the "if" statement without repeating the code?

Is there a way in javascript (or typescript) to prevent redundant object rewriting within an if statement condition? For example: if (A != null || A != B) { // do something here } // can it be done like this: if (A != null || != B) { // avoid repeating ...