Attempting to retrieve the key of an object nested within a JSON structure

I'm trying to extract all the key names from a JSON object, but I seem to be missing some when using the Object.keys method:

var myJSON = [
    {
        "Employees_Name": "Bill Sanders",
        "Work_plan_during_my_absence": "Work from home",
        "Assigned To-Manager Approval": [
            "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a8c5d1c5c9c6c9cfcddae8cfc5c9c1c486cbc7c5">[email protected]</a>"
        ],
        "AbsenceVacation_Summary": [
            {
                "Computed_Leave_Days": 2,
                "From_Date": "2018-08-20",
                "To_Date": "2018-08-21",
                "Id": "Shccbcc230_a30f_11e8_9afa_25436d674c51"
            }
        ],
        "Leave_Type": "Work from Home",
        "Reporting_Manager": "My Manager",
        "Total_Days": 2,
    }
]

Although I tried accessing keys with Object.keys(), it only gave me the top-level ones. The nested keys are missing:

var keys_arr = Object.keys(myJSON[0]);
console.log(keys_arr);

The resulting array is as follows:

"[ 'Employees_Name', 'Work_plan_during_my_absence', 'Assigned To-Manager
Approval', 'AbsenceVacation_Summary', 'Leave_Type', 'Reporting_Manager',
'Total_Days']"

I suspect that looping through this list and checking if the value corresponds to an object or array might help solve this issue, but I'm unsure how to proceed. Any guidance would be greatly appreciated.

Answer №1

To correctly navigate through your object's structure and extract nested objects along with their keys, you must recursively walk the object:

function collectKeys(inputObj, outputKeys) {
    if (Array.isArray(inputObj)) {
        for(let i = 0; i < inputObj.length; i++) {
            collectKeys(inputObj[i], outputKeys);
        }
    } else if (typeof inputObj === 'object') {
        Object.keys(inputObj).forEach(function(key) {
            outputKeys.push(key);
            collectKeys(outputKeys[key], outputKeys);
        });
    }
}
var collectedKeys = [];
collectKeys(myJSON, collectedKeys);

Explore a working fiddle here

The results will be displayed in the console.

References

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

The user score tracking database, cataloging personal scoring history

In my database, I have a table called User. Each user in this table has a field named score. I am looking to display how the score of each user has evolved over time. My dilemma is whether to store this score separately. Should I create a new database t ...

Tips for obtaining the sources of every image on a webpage and consolidating them in a single section

My goal is to preload all images on a webpage into a single division before the page loads. For example, if there are 5 images on the page (eg1.png, eg2.jpg, eg3.bmp, eg4.jpg, eg5.png), I want them to be contained within a div with the id 'pre'. ...

Pressing the send button will trigger an alert control with the value being sent as the

In my application, I had the idea to implement a straightforward panic button. The functionality of this button is as follows: When a user clicks on the panic button, an alert will appear providing them with predefined groups that they can send a panic ...

`MarkdownParser encounters bug in handling internal arrays during Newtonsoft DeserializeXNode process`

There is a JSON object with properties like: { "property1": "value1", "property2": "value2", "property3": ["value3","value4","value5"] } However, when attempting to convert it to XML using DeserializeXNode, the array is not preserved. <MyObj> ...

Having Trouble with Unevenly Spaced Child Elements in CSS Flexbox?

I'm running into a problem while utilizing CSS Flexbox to design a layout with multiple child elements. The issue at hand is that the child elements are not aligning correctly within the parent container. I aim for them to be evenly distributed and ce ...

JavaScript Cookie to Ensure Form Submission is Limited to a Single Instance

Seeking assistance with automatically submitting a form on page load using JS cookies. Here is the code I have, but it's not functioning as expected. Any guidance would be greatly appreciated. Thank you. I'm unsure about the section in my code th ...

Unable to convert the array token into an instance of the model class

I'm currently attempting to send a JSON array list to a Spring REST endpoint and implementing my logic as shown below: Model Class : public class ABCDEF{ private String A; private String B; private ArrayList<Long> C; private ArrayList<Long ...

Express.js - Struggling with Setting the Content-Type Response Header

While using Express.js, I am facing an issue with setting the Content-Type header. Even after specifying it as text/html, the response is being sent with application/octet-stream. Below is the snippet of my code: const express = require("express" ...

Configuring the IntelliJ debugger to allow for breaking inside or stepping through an NPM script

I am utilizing an NPM script that executes and produces a file within the repository. Could you please guide me on setting up the debugger to run the script in a way that allows me to perform actions like breaking inside of it and stepping through its cod ...

Can you recommend a straightforward method in Vue.js for validating the format of user input?

Here is how I have implemented an email sending feature in Vue.js: <template> <button @click="sendMail(); $emit('close')">Send</button> </template> <script> methods: { sendMail () { axios ...

Angular is able to asynchronously make an API call and then effectively utilize the returned data

I am attempting to make an API call ngOnInit(){ this.function1() } function1(){ this.userService.getUser() .then((data) => { this.user = data.user this.userM = data.userM // I have a problem here: When I console.log(this.userM) it starts of ...

Utilizing UI-GRID to showcase JSON information

I am currently in the process of fetching data from the server. [ { id:1, name:demo, request: { id: 1, localCompany: { id: 1 } } }] [{ }, { }] This is how my JSON object appears to be structured. After calling ...

Making a request using AJAX to retrieve data from an API

Looking to create an API GET request using ajax? Want a jquery function that takes an api key from the first input field and displays a concatenated result on the second input field (#2)? The goal is to make the get request to the value shown in the 2nd ...

How to activate a button only if the specified conditions are met using VueJS 3

I'm currently facing challenges while working on a form to enable a button when certain conditions are met. The form I created includes fields for name, phone number, options, and a message. Once all requirements are filled, I aim to re-enable the di ...

Tips for retrieving data from a Node.js server with a POST request in a React application

I'm currently working on a MERN authentication project, but I've hit a roadblock. Whenever the information is submitted on my register page, it triggers an add user function on the front end. async function addUser(user) { const config = { ...

`sendNodejs header not being transmitted during connection``

My nodejs application utilizes stomp to connect to a server using websockets. However, I am encountering an issue where the application is failing to send the headers that I have specified. Despite referring to clear documentation and examples on how to in ...

JavaScript Canvas - Preserve Image Transparency

I have been trying to download a snapshot of a canvas using the code below: var strMime = "image/png"; var canvas = document.getElementsByTagName('canvas')[0]; var link = document.createElement("a"); link.href = canvas.toDataURL( ...

What is the process for including a custom Jasmine matcher definition in Typescript?

I've been searching around for information on creating custom Jasmine matchers using TypeScript and it seems like a common issue. However, none of the solutions I've come across have worked for me. My setup includes: { "typescript": "2.3.2", ...

Looking to add some random circle markers to your SVG map?

I currently have a single marker displayed on an SVG Map. My goal is to scatter markers randomly across the map within the path itself. I would greatly appreciate some assistance in implementing this feature. svg { border: 1px solid; overflow: visib ...

Using JavaScript to transfer input field text into a textarea

How can I use JavaScript to insert a text or string from an input field into a text area that already contains some text? The inserted text should appear at the cursor position, and I also need a button for inserting. Is there a way to achieve this functio ...