Acquire unique keys from a JSON array without duplication

When a request is sent to an Elasticsearch cluster, the returned JSON array may look like this:

[
    {
        "_type": "Event example",
        "_source": {
            "democarrier_s": "vodafone UK",
            "m-Ecosystem_s": "iOS",
            "demo-application": "demo",
            "demo-country-code": "GB"
        }
    },
    {
        "_type": "Event example",
        "_source": {
            "democarrier_s": "Verizon",
            "m-Ecosystem_s": "iOS",
            "demo-application": "demo1",
            "demo-country-code": "US"
        }
    }
]

One might wonder how to extract all unique keys from such a document without any repetition or hard-coded values. The goal is to store these keys into an object as follows:

columns = ['_type', '_source.democarrier_s', '_source.m-Ecosystem_s', '_source.demo-application', '_source.demo-country-code'];

If you have insights on how to approach this task efficiently, your input would be greatly appreciated. We appreciate any guidance or assistance provided.

Answer №1

If you're dealing with only 2 levels, a possible solution could be:

var data = [
    {
        "_type": "Event example",
        "_source": {
            "democarrier_s": "vodafone UK",
            "m-Ecosystem_s": "iOS",
            "demo-application": "demo",
            "demo-country-code": "GB"
        }
    },
    {
        "_type": "Event example",
        "_source": {
            "democarrier_s": "Verizon",
            "m-Ecosystem_s": "iOS",
            "demo-application": "demo1",
            "demo-country-code": "US"
        }
    }
]

var keys = [];
data.forEach(function(item) {

  for (var key in item) {
    var hasProperties = false;
    
    if (typeof item[key] !== 'string') {
      
      for (var key2 in item[key]) {
        hasProperties = true;
        
        var keyName = key + "." + key2;

        if (keys.indexOf(keyName) < 0)
            keys.push(keyName);
      }
    }
    
    if (!hasProperties && keys.indexOf(key) < 0) {
       keys.push(key);
    }
 }
});

keys.forEach(function (k) { console.log(k) });

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

Unable to access $_POST parameters in PHP when making an Ajax request

My HTML file is shown below: <script> var xml = new XMLHttpRequest(); xml.onreadystatechange = function(){ if (xml.readyState === 4 && xml.status === 200) { console.log(xml.responseText); } } xml ...

What is preventing AJAX from displaying the updated JSON content?

I'm brand new to JavaScript and I'm trying to send an ajax request to retrieve the contents of a JSON file and display it in a div. Here's the code I currently have: <!DOCTYPE html> <html> <head> <script src="https: ...

Issues with Angular functionality

I'm a newcomer to Angular and I am trying to recreate this example from jsfiddle in order to experiment with nodes. However, I am encountering issues with the Angular setup. Firstly, the jsfiddle is causing confusion because the application names do n ...

Ways to embed one block of javascript code within another block of javascript code

Can you help me with inserting the following code into a specific part of my JavaScript code? The issue I am facing is that the code contains all JavaScript, and when I directly add it, the gallery crashes. <div id='gallerysharebar'> & ...

Using JavaScript to override a specifically declared CSS style

In the process of working with a database, I come across HTML that includes "spans" colored in different shades. An example would be: <div id="RelevantDiv">the industry's standard <span style="background-color: red">dummy text ever since ...

I am facing an issue where both curl and file_get_contents are not functioning properly after

When attempting to access a user's city information using coordinates, I have encountered an issue with the response not being displayed in my console. The process involves a javascript function that takes latitude and longitude data, sends it to a PH ...

Is it possible to utilize an npm package in TypeScript without a d.ts definition file?

Is it possible to use an npm package in TypeScript and Node.js without a .d.ts definition file? If so, how can I make it work? Currently, my code looks like this and I'm getting an error that says "cannot find module 'node-rest-client'" bec ...

Incorporating a GLTF Model in a Basic React Three Fiber Environment

I am attempting to incorporate a model with diffuse and bump textures into a basic scene using react 3 fiber. Despite my best efforts, I can't seem to figure out what mistake I might be making. You can view the sandbox here: https://codesandbox.io/s ...

A guide on utilizing URL parameters in Express.js to deliver images as static files

Looking to dynamically serve images from an "images" directory in my project based on user input, how can I achieve this? For instance, https://localhost:3000/images?fileName=burger This URL should display the corresponding image in the browser. If any ...

Obtain data from jQuery Data row

I am currently working on an asp.net page where I have implemented jQuery datatables. Below is a snippet of the code: <% foreach (SubmissionSearchResult result in SearchResults) {%> <tr data-name='<%=result.ID %>'> For each r ...

Is it possible to dynamically change the port for an Express server?

Here is a common question that often arises among beginners, as I had the same query when I first started Is there a way to set the port for express without manually coding it or selecting a port yourself? This was something that puzzled me during my init ...

Query the server for data and store it within the context using Next.js

My goal is to retrieve data from an API on the server-side and load it into React context for access by any component in my app. Despite trying various methods, I have yet to find a solution that meets all of my requirements. Some approaches I've expe ...

Dynamically assigning column values based on object properties

I am currently utilizing the Ionic Framework along with its grid system that is reminiscent of Bootstrap. However, I believe my query leans more towards AngularJS than specific Ionic components. Here is what I have: <ion-col *ngFor="let col of row ...

The absence of an index signature in GenericType is causing a missing declaration of the expected key/value type in Flow type

I am encountering difficulties accessing an object property dynamically with a Generic Type. Below is the code snippet: import React, { useState } from 'react' function useForm<FormValues>(initialValues: FormValues) { const [formValue ...

What is the reason behind the undefined value of "this" in this particular class method?

I have scoured the depths of the internet in search of a solution, but I am still grappling with an issue related to a JS class I am developing for a Micro Service (still learning as I go). When attempting to call a method within a class on an instantiate ...

Play a diverse selection of audio variables at random

As I prepare to transition into the view, I would like the controller to select a random audio file and play it. I'm feeling a bit lost on where to even begin with this task. Controller: var audioOne = new Audio("img/1.mp3"); var audioTwo = new Audi ...

Every initial test with Protractor ends in failure

Here are the versions I am currently using: protractor v5.1.2 chromedriver v2.33 node v6.11.4 npm 3.10.10 selenium-webdriver v3.0.1 I am a beginner with protractor and I am attempting to run the provided test natively included in protractor. The test scr ...

Tips for transferring information from one php page to another php page via ajax

I am attempting to retrieve data from one PHP page and transfer it to another page through the use of Ajax. JavaScript : $.ajax({ url: "action.php", success: function(data){ $.ajax({ url: "data.php?id=data" ...

Submitting form data does not elicit a response

I have a basic web application that performs simple queries against a MongoDB using Mongoose in Node.js with Express. Everything works fine when I use the find() method to return the entire dataset. However, I encounter issues when trying to pass form data ...

What is the best method for me to filter the values in my array?

I need to add a value to an array based on certain conditions. My code looks something like this: var newEmployee = []; $scope.employees = [{'id':1, 'new':true},{'id':2, 'new':false}{'id':3, 'new&apo ...