Tips for converting a flat JavaScript array into a multidimensional one

I'm working on an example where I need to change some values. Here is the link to access it: http://jsfiddle.net/k83hj1jb/

The current output is a flat array:

[
    {"name":"options[11][140]","value":"140"},
    {"name":"options[8][99]","value":"99"},
    {"name":"options[8][103]","value":"103"}
]

What I want instead is something like this:

[
    {
        "options":
        {
            "11":{"140":"140"},
            "8":
            {
                "99":"99",
                "103":"103"
            }
        }
    }
]

Is there an easy way to achieve this?

Answer №1

Let's refer to the array you currently have as flatArr and the desired one as nestArr.

Below is a method for calculating nestArr from flatArr:

var getNestArr = function (flatArr) {
    var nestObj = {'options': {}}, obj, opts, parts;
    for (i = 0; i < flatArr.length; i += 1) {
        obj = flatArr[i];
        opts = obj.name;
        parts = opts.replace('options[', '').slice(0, -1).split('][');
        if (!nestObj.options.hasOwnProperty(parts[0])) {
            nestObj.options[parts[0]] = {};
        }
        nestObj.options[parts[0]][parts[1]] = obj.value;
    }
    return [nestObj]; // returns an array instead of object.
};

Testing it out:

var flatArr = [
    {"name":"options[11][140]","value":"140"},
    {"name":"options[8][99]","value":"99"},
    {"name":"options[8][103]","value":"103"}
];
var nestArr = getNestArr(flatArr);
console.log(JSON.stringify(nestArr));

The above code produces this output:

[{"options":{"8":{"99":"99","103":"103"},"11":{"140":"140"}}}] 

This outcome aligns with your requirement. However, you may consider returning nestObj instead of [nestObj].

I hope this solution proves useful.

Answer №2

A simple alternative to using JavaScript is PHP, here's an example:

// starting JSON data
$jsonData = '[{"name":"options[11][140]","value":"140"},
          {"name":"options[8][99]","value":"99"},
          {"name":"options[8][103]","value":"103"}]';

// decoding JSON into a PHP array
$arrayData = json_decode($jsonData, true);

// looping through the array values
foreach ($arrayData as $val) {

    // creating a new array
    $optionValue = array();

    // accessing the value of 'name'
    $optionName = $val["name"];

    // splitting the string by square brackets
    $optionValues = explode("[", $optionName);

    // extracting two values within the option brackets
    $optionValue[] = rtrim($optionValues[1], "]");
    $optionValue[] = rtrim($optionValues[2], "]");

    // adding a new element based on the first value in the option brackets
    $newArray["options"][$optionValue[0]][] = array($optionValue[1], $val["value"]);

}

// encoding the modified array back to JSON format
$jsonData = json_encode($newArray);

// displaying the result
var_dump($jsonData);

If you have any questions or need further clarification, feel free to ask and I'll be happy to revise my answer.

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

Server-side script for communicating with client-side JavaScript applications

Currently utilizing a JavaScript library that uses a JSON file to display content on the screen in an interactive manner. (::Using D3JS Library) While working with clients, it is easy to delete, edit, and create nodes which are then updated in the JSON fi ...

Jade connecting MongoDB via Express

I'm feeling a bit confused on the best approach for transferring data from one source to another using Express. To keep it brief, here's a quick example of my current "dilemma". I've tried researching this topic, but with so many components ...

Hiding icons in a jquery datatable's table

I am currently developing an inline editing feature, and I would like to display a green checkmark in a column cell to indicate that the record has been updated. However, I need to hide it initially. This is how it looks at the moment: https://i.sstatic. ...

Acquiring the markers, however the latitude and longitude are both null - vue.js

I have been working on displaying markers on a map. When I fetched the data, everything seemed fine in Vue DevTools. The `this.markers` property also contains the data. However, to my surprise, the values for `lat` and `lng` inside the markers are showing ...

Effortless script to make a URL request and display the response status | using JavaScript with jQuery

Is there a way to use JavaScript or jQuery to request a URL or website address and display the response code? For example: request www.google.com if (response_code = 200) { print "website alive" } else if (response_code = 204) { print "not found"; } ...

Upon registration, the user's information is successfully stored in the mongoDB database, even if the selected "username" is already in

I am currently working on a web application using the MERN stack. When registering a user with an existing email either through Postman or the front-end form, the user is not added to the database. The same logic is applied to check if the chosen username ...

The light slider feature is experiencing technical difficulties within the Bootstrap model

I am experiencing an issue with the Light Slider in a Bootstrap modal. Strangely, when I press F12 for inspect element, the Light Slider starts working. For more details and to see the link provided in the comment below, can anyone offer assistance, plea ...

A more efficient method for tallying values within an object (JavaScript, React)

Is there a more efficient way to determine the count of items with a specific key/value pair in a React state? When the list is large, this method may become a bottleneck. To illustrate the question, consider the following simplified example: class App ...

Issues encountered during the installation of Electron JS

Having trouble installing electronjs in Node.js 18 LTS and NPM 10? Getting an error message like this? PS C:\Users\Administrator.GWNR71517\Desktop\electron> npm install electron --save-dev npm ERR! code 1 npm ERR! path C:\Users& ...

What is the best way to set up an on-change listener for material-ui's <CustomInput...>?

I'm currently utilizing the React dashboard created by Creative Tim. I have a question regarding how to set up an onChange listener for a Here is the code snippet for the custom input class: import React from "react"; import classNames from "classna ...

How can I maintain the toggle state when a PHP file is reloaded inside a div?

I developed a PHP script that parses a table and loads it into a specific division: <div id ="videprinter"> <script type="text/javascript"> $(function(){ function load(){ $("#videprinter").load("videprinter.php") ...

Move Ext.MessageBox.alert() to a new position in the code without altering its current functionality

I am looking for a way to reposition all Ext.MessageBox.alert() messages throughout our application without directly altering the code in our JSP pages. I can, however, include a JavaScript file. Option 1: I have found that I can reposition a message aler ...

Javascript functions fail to execute as intended

I have a project called calc, which includes various functions such as init. Within this project, there are three buttons that I am adding to the div using jquery. When a user clicks on any of these buttons, it should trigger the inputs function. Based on ...

Why are my styles not working when referenced from the .module.scss file?

Here is the code snippet from my Sublayout.module.scss file: .pl-6 { padding-left: 6rem !important; } .pr-6 { padding-right: 6rem !important; } .pl-12 { padding-left: 12rem !important; } .pr-12 { padding-right: 12rem !important; } After im ...

What seems to be causing the malfunction in this ranking function?

I created a custom function to retrieve the top five users from a JSON database. Below is the code snippet: var users = []; Object.keys(database).forEach(user => { if (!users[0]) { users[0] = user } else { var checked = false; for (let ...

Transform all the characters within p tags using the JavaScript replace method

Currently, I am dealing with data displayed on my website that comes from an XML feed. However, the issue lies in the fact that the owner of the XML feed has used grave accents (`) instead of apostrophes ('). To address this problem, I have implement ...

"Unraveling the Mysteries of Basic WebGL Sh

Trying to wrap my head around WebGL shaders, but it's like trying to untangle a mess of spaghetti. Here's what I've managed to put together: <script type="x-shader/x-vertex" id="vertexshader"> #ifdef GL_ES precision highp ...

Issue with Argument Validation in Internet Explorer 11 while using Vue.js

Encountering an error in IE11 while the code works fine in Chrome, Mozilla, and Safari. The issue arises when trying to remove a car from the garage. The error message "Invalid Argument" pops up once I attempt to remove a car from the garage section withi ...

Discovering the culprit causing a freeze on your page: Uncovering the tool or technique to identify the problematic

What is the best tool to identify resource-heavy or infinite loop JavaScript/jQuery scripts? I am currently experiencing issues with a specific template: When I open this page on Firefox 46.0.1, it freezes after a few minutes. I am having trouble pinpoin ...

Executing JavaScript in HttpClient or HtmlUnitHow to trigger javascript in HttpClient or HtmlUnit

Currently, I am using the HttpClient POST method to perform a specific action on a website. This involves using Javascript for an ajax connection which generates a unique requestID in the form of var reqID = Math.floor(Math.random()*1000001);. I need to ac ...