What is the best way to change JSON into a key-value dictionary with TypeScript?

Here is a JSON example that I am working with:

{
    "MyTest:": [{
            "main": {
                "name": "Hello"
            },
            "test2": {
                "test3": {
                    "test4": "World"
                },
                "test5": 5
            }
        },
        {
            "main": {
                "name": "Hola"
            },
            "test6": [{
                    "name": "one"
                },
                {
                    "name": "two"
                }
            ]
        }
    ]
}

My goal is to convert it into an array of arrays with key-value pairs.

[[main.name: "Hello", test2.test3.test4: "World", test2.test5: 5] , 
[main.name = "Hola", test6.name: "one", test6.name: "two"] ];

I am looking for a function like "is leaf" that can help me identify the values in the JSON structure.

If you have any advice on how to iterate deeply through this data, please share as it would be greatly appreciated.

Answer №1

The function flattenObject() is designed to transform a nested object into a flat one, where keys are constructed by joining all sub-keys. This recursive function first checks if the current value is an object. If it is, it uses _.flatMap() to iterate through each property and call itself recursively with the collected keys so far. On the other hand, if the value is not an object, it simply returns an object with a single property containing the joined keys and the value.

After iterating through the object and collecting { key: value } objects, the final step involves merging these objects into a single flat object.

const flattenObject = val => {
  const inner = (val, keys = []) => 
    _.isObject(val) ? // check if it's an object or array
      _.flatMap(val, (v, k) => inner(v, [...keys, k])) // iterate and call fn with value and collected keys
      :
      { [keys.join('.')]: val } // return joined keys with value
      
  return _.merge({}, ...inner(val))
}

const obj = {"MyTest":[{"main":{"name":"Hello"},"test2":{"test3":{"test4":"World"},"test5":5}},{"main":{"name":"Hola"},"test6":[{"name":"one"},{"name":"two"}]}]}

const result = obj.MyTest.map(flattenObject)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

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

Steps for populating a ListView with JSON data

I'm fairly new to Android and Java and I have a question. How can I efficiently load a JSON result obtained from an HTTP request into a ListView? In the onPostExecute method below, I am able to retrieve the result but I'm unsure how to display it ...

"Utilizing Angular's ng-repeat to house multiple select dropdown

I'm dealing with a scenario like this: <span ng-repeat="personNum in unit.PricePerson"> {{personNum}} <select ng-model="personNum" ng-options="o as o for o in unit.PricePerson track by $index"></select> & ...

Issue with jqGrid not showing JSON data received from Java application

My Java Service Implementation: @RequestMapping(value="/refreshInterviewServiceList1", method = RequestMethod.GET) public @ResponseBody JSONObject refreshInterviewServiceList1() throws JSONException{ List<ReportInterview> reportInterview = repo ...

Ways to retrieve the body in a REQUEST using node.js

I am struggling to get actual data back when I call my function, instead I only receive an empty object {}. const Ocr = (file,req,response) => { const options = { method: "POST", url: "https://api.aiforthai.in.th/ocr& ...

React modules imported in ES6 not functioning as anticipated

I'm currently facing a problem when trying to import a react class into a container. The structure of my files is as follows: ├── components │ ├── Header │ │ ├── Header.js │ │ └── index.js │ └── ...

"Trouble with import aliases in a create-react-app project using craco: How to fix it

IMPORTANT UPDATE: Following Stackoverflow guidelines and for the convenience of everyone, I have created a concise reproducible example to showcase the bug in question: https://github.com/shackra/stackoverflow-alias-bug UPDATE 2: Just as an additional no ...

React Native - Caution: It is important for every child in a list to have a distinct "key" prop assigned to it

In my app, I am using FlatList to display a list of products with the help of Products.js and ProductCard.js. Products.js: const Products = ({navigation}) => { const renderItem = ({item}) => ( <ProductCard item={item} onClickHa ...

Remove the JSON object by comparing IDs between two JSON objects in JavaScript or Node.js, deleting it if the ID is not found

let data = fetchData(); let anotherData = getAnotherData(); let result = data.reduce((accumulator, current) => { if (!accumulator[current.system.name]) { accumulator[current.system.name] = {}; } let detailsObject = {}; Object.keys(current. ...

Using jQuery's slideToggle feature to hide content when clicked again or when a different button is

I have a challenge with creating toggle buttons that require specific functions: 1) Display content on the first click (this is working) 2) Conceal content when another button is clicked (this is also working) 3) Hide content on the second click (this i ...

Guide on updating the form structure with ajax

Lately, I've been working on a contact module with 3 columns: name, email, and phone. There's also a +1 button that adds a new row to input another contact using ajax. However, a problem arises when updating the structure as the data in the old c ...

When jQuery fails to detach() due to the presence of an input tag

I have a situation where I am trying to rearrange elements within a table. Everything works fine, until I introduce a tag, which triggers this error message:</p> <pre><code>Error: this.visualElement is undefined Source File: http://192. ...

The "void" type cannot be assigned to the type "ObservableInput<{}>"

I recently encountered this issue after updating to TS 2.2.2, and I suspect that is the root cause... While the code still functions properly, I am now seeing this error. I attempted various solutions such as returning an empty observable, catching the re- ...

Implement a loading bar on the entire page in Vue.js while a request is being made

There is an "edit" button on my page which allows me to edit certain elements and either save or close without saving. I would like to implement a loading bar that displays when the user clicks the "save" button, indicating that the data is being processe ...

Sending CoreData data as JSON to the Server

As a newcomer to iOS development, I am currently exploring the process of sending a JSON string to a webserver and receiving relevant information in return. On the initial page, I collect the user's first name and last name before generating an ID for ...

How to Fetch Data Using jQuery AJAX in PHP Without Page Refresh

I am trying to prevent the page from refreshing when clicking on a select option, but when I do so, the data does not get updated. Here is the code: echo "<form name='frmtopdevotees' method='post' action='topuser_load.php&apos ...

Older versions of Android, specifically Android 7 or lower, seem to encounter issues with Apis in React Native when utilizing axios. Fortunately, this problem doesn

For fetching the data, I utilized the 'axios' library. Surprisingly, it works flawlessly on newer Android devices (specifically Android 9 and 10). However, when it comes to older devices like Android 7 or earlier, a persistent Network Error occur ...

How to ensure a table in MaterialUI always maintains full width without requiring horizontal scrolling in CSS?

After attempting to allocate each widthPercent value on the TableHeader so they sum up to 100%, I am still experiencing the presence of a scroll bar. I have tried setting fixed widths for each column, but this results in excess space on the right side dep ...

Is there a concept in JavaScript that includes a data structure called a "matrix" with elements arranged in a grid-like format accessed by

I'm not familiar with the terminology, but I'd like to simplify it: var topicList1 =['hello','hallo', ..., 'hej']; var topicList2 =['a','b',...,'c']; ... var topicList999 =['x,&apo ...

The functionality of cropping is not supported within a Bootstrap modal

I have been using ngimgcrop successfully to crop images within my application. However, I encountered an issue when trying to display the cropped images inside a uibmodal (AngularJS modal). Despite trying various solutions, such as using ng-init, I was una ...

Unable to retrieve JSON data on Android smartphones

By utilizing a local JSON file, I am fetching data using $.getJSON and displaying it using jQuery mobile. $('body').off('tap').on('tap', 'ul li', function(event) { var jqxhr = $.getJSON("one.json", function(data ...