Improprove the efficiency of flattening an array containing nested JSON objects using JavaScript

Supposed to be an array structured like this:

[
     {
        "key_set1": {
            int_val: 3,
            arr_val: [
                1,
                3,
                4
            ]
        }
    },
    {
        "key_set2": {
            string_val: "foo"
        }
    }
  ]

I aim to flatten the inner object keys into a new root object, resulting in:

{
    "key_set1": {
        "int_val": 3,
        "arr_val": [
            1,
            3,
            4
        ]
    },
    "key_set2": {
        "string_val": "foo"
    }
}

Considerations:

  • The nested structure may have N levels with N > 10
  • The structure is valid JSON not Javascript object (atomit/non-atomic types)
  • The input json file can be large (hundreds of KBytes)
  • Must use JavaScript V8 / ECMAScript6 for processing
  • Processing time needs to be within milliseconds
  • Variants of this mapping will involve parsing input JSON and modifying values using methods like map

I seek the most optimized solution utilizing built-in methods such as forEach, fast iterators for, while, etc., for optimal performance in best/worst cases.

Answer №1

From my understanding, you prefer to swap out the array with an object and use the first level key as the new key for the resulting object.

let arr = [{ "key_set1": { int_val: 3, arr_val: [1, 3, 4] } }, { "key_set2": { string_val: "foo" } }],
    obj = {};

arr.forEach(function (a) {
    let key = Object.keys(a)[0];
    obj[key] = a[key];
});

console.log(obj);

Answer №2

If you are aiming to achieve the best optimization for your code, it is advisable not to utilize Array.map in this scenario since it generates a new array. Instead, opt to swiftly iterate through the list array and populate the new flattened object. Here is an example of an "optimized" solution:

var flattened = {}, len = list.length;
while (len--) {
    Object.keys(list[len]).forEach((k) => (flattened[k] = list[len][k]));
}
console.log(JSON.stringify(flattened, 0, 4));

The resulting output will be:

{
    "key_set2": {
        "string_val": "foo"
    },
    "key_set1": {
        "int_val": 3,
        "arr_val": [
            1,
            3,
            4
        ]
    }
}

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

Utilizing separate JavaScript files in Bootstrap 5: A guide to implementation

I am currently using Bootstrap, but I am looking to decrease the size of the Javascript files being used. My main requirements are dropdown/collapse and occasionally carousel functionalities, so I only want to include those specific scripts. Within the "d ...

What is the best way to set a specific maximum size for the dropdown selector in Material UI's TextField component?

Working on a Sign up Page involves prompting users to select their location from a dropdown list of different countries. However, the issue arises when the dropdown list covers the entire screen, making it difficult for users to navigate. Is there a way to ...

Selecting a full table row activates a top-up popup

I have successfully implemented a script in Javascript to enable full table row selection as shown below. <script type="text/javascript"> $(function() { $('#link-table td:first-child').hide(); $('#link-table tr').hover(func ...

Issue: Headers cannot be set after they have been sent. This is a problem in node.js

I'm trying to create an application that allows users to execute commands via a URL, but I keep encountering this error message: _http_outgoing.js:346 throw new Error('Can\'t set headers after they are sent.'); ^Error: Can't ...

SQL Server - JSON data type enumeration

Supplied declare @json varchar(max)='{ "name":"John", "age":30, "cars": [ { "make":"Ford", "models":[ "Fiesta", "Focus", "Mustang","Vintage"] ,"price":[1100,200,300,999]}, { "make":"BMW", "models":[ "320", "X3", "X5" ] }, { "make":"Fiat", ...

Converting an ISO date to a standard JS date: The straightforward approach

Can anyone help me with converting an ISO date to a Standard JS Date format? The specific format I need is: Mon `Jul 20 2020 14:29:52 GMT-0500 (Central Daylight Time)` I would appreciate any guidance on the best approach for achieving this. Thank you in a ...

The output of jquery's val() function will not show the actual value

Is it proper to use html() for setting content in non-form elements like divs? This question has come up a few times, which I wasn't aware of. I've been working on setting a value after fetching comments through a $.ajax call. When I check the v ...

Tips for extracting the chosen text during a 'change' event

I need to access the text of the currently selected object. When I use $(this).text(), I end up getting all available selections I have attempted the following methods without achieving the desired result: $(this).text() $(this).selected() $(this).se ...

How can we eliminate all elements from jQuery except for the first and second elements?

HTML <div class="geo_select"> <h3>header 3</h3> in Above HTML code i want to remove all element except <h3> and default content<div> inside the <div class='geo_select'> in jquery.. How to remove all ...

Using Angular select asynchronously within a custom directive

Despite my efforts, I am struggling to get an angular select with async to work properly. It seems to be mostly working, but not entirely. Consider the controller below: $scope.stuff = {}; $scope.stuff.blah = "SOME_KEY"; External.list().then( function ...

When render returns another component, React does not invoke componentWillMount

Here is my code setup: const Dashboard = React.createClass({ getInitialState(){ return { user: JSON.parse(localStorage.getItem('user')) }; }, componentWillMount(){ var self = this; $.get({ url: 'http://127 ...

Tips for enhancing a search algorithm

I am currently working on implementing 4 dropdown multi-select filters in a row. My goal is to render these filters and update a new array with every selected option. Additionally, I need to toggle the 'selected' property in the current array of ...

The appearance of an escape character has been detected within the JSON output

Currently, I am facing an issue while writing to an Avro file that is being sent to Snowflake. One of the fields in this process contains a blob of JSON data. The JSON structure consists of various elements and values, and its format is dynamic and unknow ...

AngularJS module is experiencing issues with loading properly

Can someone please help me understand what the issue is? I am new to AngularJS and may have overlooked something. Below is my simple HTML code: <!DOCTYPE html> <html> <script type="text/javascript" src="angular.js"></script> ...

Using a local function within Node.js and referencing it with the <%%> tag in a document

I am currently working with Node.js and attempting to utilize a local function within a document that requires the JSON I send in the res.render. Is there a method to achieve this? Below is an example of how I attempted to implement it: <%local_vari ...

Ways to reach component method via router

When making an Ajax request and displaying the data in a table component, I encounter an issue where I need to extract the clicked data for use in another Ajax request within a different component that is called through React-Router. The challenge lies in ...

What is preventing the control from being passed back from the PHP file to the AJAX success function?

My website is built using PHP, Javascript, and AJAX. Below is the essential code snippet: JS code (AJAX function): $("#btn_add_event").click(function(){ var strSeriaze = $( "#formAddEvent" ).serialize(); url = $( "#formAddEvent" ).attr('act ...

Animate the leftward disappearance of a div to make it vanish

My goal is to create a user interface where users can navigate through different divs. Here is the HTML code: <article id="realize" class="realizeBox"> <div class="shown"> <div class="heading"> <h2>Realisati ...

Prevent additional clicks on the image

Currently, I am dealing with a situation where I have a list containing a jQuery handler for mouse clicks. The dilemma is that I need to insert an image into the list, but I want clicking on the image to trigger a different function than clicking elsewhere ...

The child's status is not displaying correctly

I am in the process of developing a blackjack app and facing an issue with re-rendering hands after the initial deal. I have tried updating the state in App.js and passing it to PlayerHand.js for rendering, but the child component does not refresh despite ...