What is the most efficient way to optimize the time complexity of a JSON structure?

Here is the input JSON:

const data = {
  "38931": [{
      "userT": "z",
      "personId": 13424,
      "user": {
        "id": 38931,
        "email": "sample",
      },
    },
    {
      "userType": "z",
      "personId": 19999,
      "user": {
        "id": 38931,
        "email": "sample",
      },
    }
  ],
  "77777": [{
    "userT": "z",
    "personId": 55555,
    "user": {
      "id": 77777,
      "email": "sample",
    },
  }]
}

The desired output should look like this:

{
  "38931": {
    "13424": {
      "userT": "z",
      "personId": 13424,
      "user": {
        "id": 38931,
        "email": "sample"
      }
    },
    "19999": {
      "userType": "z",
      "personId": 19999,
      "user": {
        "id": 38931,
        "email": "sample"
      }
    }
  },
  "77777": {
    "55555": {
      "userT": "z",
      "personId": 55555,
      "user": {
        "id": 77777,
        "email": "sample"
      }
    }
  }
}

While I have achieved the correct result, I am still looking for a more efficient approach to achieve O(n) complexity. The current method involves destructuring in the reducer function which leads to O(n^2) complexity in the last section.

const data = {
  "38931": [{
      "userT": "z",
      "personId": 13424,
      "user": {
        "id": 38931,
        "email": "sample",
      },
    },
    {
      "userType": "z",
      "personId": 19999,
      "user": {
        "id": 38931,
        "email": "sample",
      },
    }
  ],
  "77777": [{
    "userT": "z",
    "personId": 55555,
    "user": {
      "id": 77777,
      "email": "sample",
    },
  }]
}

const accumulatorList = (acc, id) => {
  acc.push(data[id]);
  return acc;
}
const accumulatorObject = (acc, [key, value]) => {
  const {
    user: {
      id
    }
  } = value;
  acc[id] = {
    ...acc[id],
    [key]: value
  };
  return acc;
}

// Concatenate arrays from main object (data), convert to 1D array, transform to hashMap with key "personId",
// then transform into an array for iteration using Object.entries and create the final object result.

const people = Object.keys(data)
  .reduce(accumulatorList, [])
  .flat()
  .reduce((acc, obj) => {
    acc[obj.personId] = obj;
    return acc;
  }, {});

const finalResult =
  Object
  .entries(people)
  .reduce(accumulatorObject, {});

console.log('finalResult', finalResult);

If you have any suggestions on how to achieve O(n) complexity, please let me know. Thank you!

T = O(n)

Answer №1

I believe a more efficient solution can be achieved by iterating through the top-level object's entries and converting the array of objects under each key into an object using Object.fromEntries:

const data = {
  "38931": [{
      "userType": "z",
      "personId": 13424,
      "user": {
        "id": 38931,
        "email": "sample",
      },
    },
    {
      "userType": "z",
      "personId": 19999,
      "user": {
        "id": 38931,
        "email": "sample",
      },
    }
  ],
  "77777": [{
    "userType": "z",
    "personId": 55555,
    "user": {
      "id": 77777,
      "email": "sample",
    },
  }]
}

const transformedData = Object.fromEntries(Object.entries(data)
  .map(([key, value]) => [key,
    Object.fromEntries(value.map(obj => [obj.personId, obj]))
  ])
)

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

If modifying the object in place is acceptable, a simpler approach using forEach can be used:

const data = {
  "38931": [{
      "userType": "z",
      "personId": 13424,
      "user": {
        "id": 38931,
        "email": "sample",
      },
    },
    {
      "userType": "z",
      "personId": 19999,
      "user": {
        "id": 38931,
        "email": "sample",
      },
    }
  ],
  "77777": [{
    "userType": "z",
    "personId": 55555,
    "user": {
      "id": 77777,
      "email": "sample",
    },
  }]
}

Object.keys(data).forEach(key => data[key] = Object.fromEntries(data[key].map(obj => [obj.personId, obj])))

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

Nextjs introduces an innovative "OnThisDay" functionality, leveraging getServerSideProps and Date.now() to provide real-time information

I am currently working on adding an "OnThisDay" feature in my Nextjs project, inspired by Wikipedia's style of displaying events that happened on a specific date. To achieve this, I have implemented a function structured like the following code snippe ...

Using Angular 2 to create a toggle button that changes based on a JSON response

I am attempting to switch the button based on the response from the backend. If the response is Yes, the toggle button should be set to ON; if the response is No, then it should be turned OFF. Here is the HTML code I have: <div class= ...

Error: script 'start' is not defined on Heroku

Hello there! I'm currently working on deploying an application to Heroku from my GitHub repository. To ensure that everything runs smoothly, I made some modifications to the start script in the package.json file. Specifically, I adjusted it to point t ...

How can you run a function in JavaScript or TypeScript that is stored as a string?

Is there a way to call a function that is stored as a string? For example: var dynamicFun = `function Hello(person) { return 'Hello' + person; }` In this case, the dynamicFun variable can store any function definition dynamically, such as: var ...

What is preventing me from obtaining the select and input values?

I'm currently facing an issue where I am unable to retrieve the values of customInput and customSelect and store them in the state. The challenge arises when trying to integrate these components into a react dashboard material-ui setup. Strangely, whe ...

Utilize the serialized data to pre-fill the form fields

After using the serialize() function on my form and saving the string, I am now looking for a function that can repopulate values back into the form from the serialized string. Is there such a function available? ...

What is the most effective way to retrieve the default value of ng model?

When working with php and angular, I am trying to set a value in ng model from a php expression. However, when I try to read the ng model value from the controller, it is showing up as null. <input ng-model="id" ng-init="id= '<?php echo $userID ...

CSS transition fails to revert

My standard opacity animation is not working in reverse order. Here is a link to the JSFiddle example. According to the documentation, it should work automatically. Since I am new to JavaScript, I am unsure if this issue lies in my code or if the CSS anima ...

How can I link to a different field in a mongoDB Schema without using ObjectID?

I have created two schemas for books and authors: const bookSchema = new mongoose.Schema({ title: String, pages: Number, description: String, author: { type: mongoose.Schema.Types.ObjectId, ref: 'Author' } }); const Book = mongoose.model ...

Exploring the intricacies of using jquery text() with HTML Entities

I am having difficulty grasping the intricacies of the jquery text() function when used with HTML Entities. It appears that the text() function converts special HTML Entities back to regular characters. I am particularly uncertain about the behavior of thi ...

Implementing jQuery slideDown effect on a nested table element

I am facing an issue where the nested table does not slide down from the top as intended when a user clicks the "Show" button. Despite setting the animation duration to 500ms with jQuery's slideDown() function, the table instantly appears. I am using ...

Creating TypeScript declaration file for exporting JavaScript function

I'm a beginner with TypeScript and I want to learn how to create a declaration file for a custom JavaScript function. I attempted to do this, however, I encountered an error stating "Could not find a declaration file for module './main'." Ad ...

When working on a Vue project, the Navbar @click functionality seems to

Having trouble with my navbar search form <form action="" method="post" class="search"> <input type="text" name="" placeholder="поиск" class="input" v-model="alls ...

How can you prevent the 'Script not responding' error when using Reverse AJAX / Comet?

My worker thread is responsible for sending requests to the server using XMLHttpRequest. The request is directed to a php file which checks the integrity of client information. If the client requires new data, it is sent. Otherwise, the server continuously ...

Struggling with the proper state updating in React hooks when using dynamic naming conventions?

I am currently working with a react component that handles login requests to my server. This component is housed within a modal using Material UI. <TextField onChange={handleChange} autoFocus name="email" ...

Boosting your website with a slick Bootstrap 4 responsive menu that easily accommodates additional

I have incorporated a main menu in my website using the Bootstrap 4 navbar. However, I also have an additional div (.social-navbar) containing some extra menu items that I want to RELOCATE and INSERT into the Bootstrap menu only on mobile devices. Essentia ...

By default, the text area element in Vue or Nuxt will send a message to the console

Every time I include a textarea html element in my Vue/cli or Nuxt projects, this message appears in the console. Is there a way to prevent this message from showing up in the console? <textarea rows="5" cols="33"> This is a textarea. < ...

"Executing the jar file results in 'JAX-RS MessageBodyWriter not found for media type=application/json' error, however running mvn:exec works perfectly

I am facing a challenge while trying to package my maven project. Initially, I developed and tested it using mvn:exec and everything worked perfectly fine. However, after generating the jar file with dependencies using mvn package, I encountered an issue. ...

Converting Buffers to Binary with JavaScript Node.js

I've been working with Node.JS Buffers to send and receive packets, but I'm struggling to figure out how to convert these buffers into binary representation. I attempted the following code snippet, but it didn't yield the expected results co ...

Show Json file in a randomized sequence

I want to display the data in my table in a different order than it appears in the file content. The file contains information about houses for sale. The JSON file returned from the server lists the houses based on the number of "days for sale", with the ...