transform a nested JavaScript object into a one-dimensional array

There is a JavaScript object in the following format:

{
  "draw": "",
  "columns": [
    {
      "data": "userid",
      "name": "",
      "searchable": true,
      "search": {
        "value": "",
        "regex": false
      }
    }
  ]
}

I want to transform it into a single-dimensional object like this:

{ 
 "draw" : "",
 "columns[data]": "userid",
 "columns[name]": "",
 "columns[searchable]": "true",
 "columns[searchable][value]": "",
 "columns[searchable][regex]":"true"
}

The main object can have multiple layers of depth and may contain objects and arrays.

Any suggestions or ideas are greatly appreciated since JavaScript is not my strong suit.

Answer №1

To handle this scenario, I would implement a recursive function that takes a property of the original object and the path to that object as arguments. If the property is not an object, the function will add the value to the path. If the property is an object, the function will iterate through its properties and call itself recursively.

var object = {
  "draw": "",
  "columns": [{
    "data": "userid",
    "name": "",
    "searchable": true,
    "search": {
      "value": "",
      "regex": false
    }
  }]
};

console.log(flatten(object));

function flatten(object) {
  var result = {};
  innerFlatten(object, "");
  return result;

  function innerFlatten(object, path) {
    if (typeof object !== "object" || object === null || object instanceof Date) return result[path] = object;
    if (!Object.keys(object).length) return result[path] = object;
    for (var key in object) {
      innerFlatten(object[key], path ? (path + "[" + key + "]") : key);
    }
  }
}

Answer №2

To achieve this, you can remove the array from the columns property and set it to the 0 index value.

let example = {
  "draw": "",
  "columns": [
    {
      "data": "userid",
      "name": "",
      "searchable": true,
      "search": {
        "value": "",
        "regex": false
      }
    }
   ]
}

example.columns = example.columns[0]

console.log(example)

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

How can I replace any non-alphanumeric characters in a string with an underscore using JavaScript or TypeScript?

There is a unique string generated from an external data source that I cannot manage. The system above me necessitates the IDs to adhere to this rule: "Field names should start with a letter and can solely consist of letters, numbers, or underscores (&apos ...

Ember.js: Storing function prototypes as objects

My interface consists of four vertical panels: The first panel displays the menu for selecting data The second panel allows you to choose a filter from a list The third panel shows the results based on the selected filter The fourth panel displays detail ...

Using Node.js to parse XLSX files and generate JSON output

Recently, I came across an extremely well-documented node_module known as js-xlsx Curious: How can I convert xlsx to json format? This is the structure of the excel sheet: The desired json output should resemble the following: [ { "id": 1, "H ...

Tips for enhancing the width of the extrude shape in the x and z axes using Three.js

After creating a shape using extrude geometry, I found that I needed to increase the thickness along the x and z axes. Although I used bevelThickness to increase the thickness along the y axis, I still need to adjust it further. For reference, please see ...

Calculating a Price Quote

I have created a dynamic quote calculator for a Next.js project that allows users to calculate prices based on word count and selected languages. Currently, the price is calculated using a fixed rate of 0.05 per word. 'use client'; import { useS ...

Unable to retrieve selected value with AJAX

My select box is set up with some values, and I'm using AJAX to send data to PHP and display that data inside a <div>. However, my code doesn't seem to be working properly. Interestingly, when I used a button to get the value from the sele ...

Steps for creating a PDF file from an HTML page using JavaScript coding

I'm developing an HTML5 hybrid iPad app and need to create a PDF file of a report generated on one of the pages. I would like to save this PDF on the iPad. Can you provide assistance with achieving this task? I am utilizing JavaScript and mobile jQuer ...

Having issues with npm python-shell integration within electron framework

I'm currently attempting to establish a connection between a python script and an Electron app by utilizing the npm's python-shell package. The requirement is for the script to be executed whenever a button is clicked. So, let's assume my d ...

Implementing IBAN as the default option in Stripe's PaymentElement

The functionality of the react-stripe-js library's IbanElement includes various options such as supportedCountries and placeholderCountry: <IbanElement ... options={{ supportedCountries: ["SEPA"], placeholderCountry: "DE& ...

Storing JSON strings in PHP differs from storing them in JavaScript

Using JavaScript, I can save a cookie using JSON.stringify(), which saves the cookie directly like this: '[{"n":"50fb0d0cc1277d182f000002","q":2},{"n":"50fb0d09c1277d182f000001","q":1},{"n":"50fb0d06c1277d182f000000","q":1}] Now, I am sending this t ...

Is there a way in Jquery to retrieve the id of the clicked element and modify its name?

I am using a drag-and-drop website builder that utilizes HTML blocks, each with a unique ID. After dropping the blocks onto the canvas, I want to create a navigation menu that links to the IDs of each block. How can I retrieve the current ID of the block I ...

The element's height appears to be fluctuating unexpectedly when I attempt to adjust it using percentage values within a narrow range

I'm utilizing React and Bootstrap in this project. Here's an overview of my code: I have an element with height set to 0, in rem. My goal is to make the height of this element increase as I scroll down the page, creating the illusion that it is ...

How to reposition the Bootstrap navbar Logo from the left to the center

I am looking to change the ordering of Bootstrap 4 Navbar. Currently, the logo is on the left side, but I want it in the center with menus on both sides. Can someone help me with changing this order? Check out the current Navbar layout below: <nav c ...

Retrieve a single document from Firestore and assign it to a variable

While I'm still new to NodeJS, I'm currently working on retrieving a single User document from Firestore. const fs = firebase.firestore(); const usersRef = fs.collection('users'); let findUserByContact = (contact) => { let res ...

"Troubleshooting issue: Module fails to reload following JSON.parse error

For QA testing purposes, we have a test page that allows our QA team to replicate server behavior by passing JSON to a mock service. Everything functions correctly when valid JSON is used, but if invalid JSON is provided, an error is returned - which is ex ...

Retrieving display format or formatted value from an object with Moment.js

I am currently working on a project using Angular and Material2. Within this project, I have created a moment object in the following way: myDate = moment.utc(new Date()).format("YYYY-MM-DD HH:mm:ss"); This object is then passed as an argument to ano ...

Trouble with AJAX request on iPad, works perfectly on desktop

Here is some of my custom plugin code (function ($) { $.fn.createGallery = function(options) { var theObject = $(this); var settings = $.extend({ // Default settings. server: 'http://localhost/jQuery%20Gall ...

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 ...

What is the best way to assign the "active" class to a navigation list item using JavaScript within Bootstrap 4?

Update: just to clarify, I'm working on activating the navbar button based on the current page. I have a navigation bar set up and I am trying to dynamically add an "active" class to the li element when you are on that specific page. However, for som ...

Harnessing the power of flexbox for data visualization

Trying to use flexbox to display data from a dataset in my code. Here is the code snippet: <div ng-app="myapp" ng-controller="FirstCtrl"> <div ng-repeat="name in names" class="graph-wrapper"> <div class="aside-1 content"> ...