Guide to reading JSON files with a personalized approach

Below is a JSON object structure that I am working with:

{
 "db": {
   "name": "db",
   "connector": "memory"
 },
"MySql": {
   "host": "localhost",
   "port": 3306,
   "database": "users",
   "username": "root",
   "password": "",
   "name": "MySql",
   "connector": "mysql"
 },
"postgreDS": {
   "host": "localhost", 
   "port": 1234,
   "database": "abc", 
   "username": "postgres", 
   "password": "abc",
   "name": "postgreDS",
   "connector": "postgresql"
 }

From the above JSON object, I am looking to extract the following keys:

{"db", "MySql", "postgreDS"}

I am seeking guidance on how to extract this information using JavaScript and also how to access the subkeys along with their respective values.

Answer №1

If you're in need of extracting the keys from nested objects, you can utilize Object.keys:

var keys = Object.keys(obj); // [ "db", "MySql", "postgreDS" ]

If your goal is to retrieve values from nested objects based on a specific key, here's a versatile function that will generate an array of values:

function retrieveValueFromKey(obj, key) {
    return Object.keys(obj).map(function (el) {
        return obj[el][key];
    });
}

retrieveValueFromKey(obj, 'name'); // [ "db", "MySql", "postgreDS" ]
retrieveValueFromKey(obj, 'connector'); // [ "memory", "mysql", "postgresql" ]

VIEW DEMO

Answer №2

Here is an example of a similar code snippet (using the variable data instead of obj):

var dataKeys = [];
for(var key in data){
    dataKeys.push(key);
}
console.log(JSON.stringify(dataKeys)); // ["name", "age", "gender"]

Answer №3

Check out the JSFIDDLE,

Javascript

$(function(){
var result = {};
var elements = {
 "db": {
 "name": "db",
 "connector": "memory"
  },
"MySql": {
   "host": "localhost",
   "port": 3306,
   "database": "users",
   "username": "root",
   "password": "",
   "name": "MySql",
   "connector": "mysql"
  },
"postgreDS": {
   "host": "localhost", 
   "port": 1234,
   "database": "abc", 
   "username": "postgres", 
   "password": "abc",
   "name": "postgreDS",
   "connector": "postgresql"
 }};
 
for(var key in elements) {
    result.push(key); // result will hold the expected output
}
console.log(result);
});

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

What's the optimal method for integrating bootstrap.css into a Nuxt project?

Here is a snippet from my nuxt.config.js file: head: { link: [ { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }, // load bootststrap.css from CDN //{ type: 'text/css', rel: &ap ...

Using ng-pattern to validate that a text field does not conclude with a particular term

In this code snippet, I am attempting to prevent a textfield from ending with any of the specified letters in the $scope.pointPattern variable. $scope.pointPattern = /^(?!.*ess|ence|sports|riding?$)/; $scope.error = "not valid"; Upon executio ...

Tips for avoiding automatic updates to .js scripts after pressing F5

Is there a method to stop a JavaScript script from resetting when the user refreshes the page? For instance, if I have a picture slider that is constantly changing images, I would like the script to continue where it left off instead of starting over wit ...

Using the https module in Node.js to transfer a file to a PHP server

What is the best method to send an HTTP post request that includes a jpg file to a php server using the node https module? I attempted to use the request module, but it is unreliable (timing out most of the time) and already deprecated. Here is the functi ...

How can I assign a default value for a multiple select dropdown list in AngularJS?

I am currently facing an issue with my multiselect dropdown. The code for the dropdown is as follows: <select id="year" multiple ng-model="type" ng-disabled="!type1" > <option value="all" selected>all</option>; <option value= ...

What is the best way to eliminate an item from an array in JavaScript or AngularJS?

I'm attempting to eliminate objects from an array and retrieve the resulting array. I've been using a remove function, but it's not functioning as expected. Here is the input I'm working with: The goal is to remove all values in the ar ...

Displaying the preselected option in a Select dropdown menu using Angular

Here is the code snippet I have: <select label="people" id="ppl" [(ngModel)]="Selectedppl" (ngModelChange)="onPplSelection($event.target.value)"> <option>select people</option> <option *ngFor="let x of peopleList" [ngValue]="x"> ...

Issue when deserializing JSON credentials for Google Sheets API in C#

I have been attempting to utilize a service account in order to access the GoogleSheets API, but I am encountering issues with my .json file. Below is the code I am using: try { string[] scopes = new string[] { SheetsService.Scope.Spreads ...

Easily changing the state of a specific array item using React

I'm having trouble updating the state of a specific item in an array called reviews. Can someone guide me on how to achieve this? The following code snippet is not working as expected: this.setState({ reviews[2].current: true }); Below is the comp ...

What is the best way to organize an array of JSON objects stored in a variable?

Within my Postgres function, I perform calculations on data and store them as jsonb objects in a variable of jsonb array type. For instance: _some_variable := [{"name": "Product 1", "amount": 12, "created":'20 ...

Manipulating multidimensional arrays in PHP and converting them to JSON format

I have a MySQL table with the following fields: id | building | title | parent Now, I am looking to implement a timeline calendar using fullcalendar.io. This is the structure I aim to create: { id: '1', building: '460 Bryant', title ...

Troubleshooting a Vue 2 component's prop receiving an incorrect value

I'm currently working on creating a menu that navigates between categories. When a category has a sub-category, it should return a boolean value indicating whether it has a sub-category or not. <template> <select><slot></slot ...

Issue with Ionic toggles not updating the correct local storage entry

Encountering an issue with ionic toggles where changing any toggle affects only the last if statement below in local storage. Here is the list of toggles... $scope.settingsList = [ { text: "GBP", checked: gbpON }, { text: "USD", checked: usdON } ...

Error: Unable to access attachShadow property as it is null and cannot be read

Having an issue with my vue component where I am getting a TypeError: Cannot read properties of null (reading 'attachShadow') error when building it as a web component. Here is the command I am using to build the vue component: vue-cli-service bu ...

The error message "Cross-origin requests are only supported for protocol schemes" may occur in Google Chrome when using Adobe Animate CC

I've been following this tutorial from Greensock Quick start and have downloaded the sample files. Everything was working perfectly, until I added images to the banner and published it from Adobe Animate CC. The banner ad works fine online, but if I t ...

What is the best way to modify an array's property in order to achieve the desired outcome when using json_encode?

Expected Result ['#ff0000','#4caf50','#4caf50','#4caf50','#00bcd4','#00bcd4','#4caf50','#4caf50'] The output I am receiving is as follows: ["'#ff0000','#4caf5 ...

What is the best approach to dynamically load html table cell data into a table with changing headers in a React application?

Currently, I am in the process of developing a <table> using React version 0.14.6. This table consists of column headers that are dynamically added to the <thead> section of the table: CourseTable.js: import CourseList from './CourseList ...

UPDATE: Choosing several classes and then toggling the classes independently for each one

I have managed to make this work, but I am considering if there is a more efficient solution. My objective is to modify the divs using classes exclusively. I aim to toggle 4 classes with just one click. First, I obtain the class for the button and then a ...

Parallel mapping with simultaneous multiple inserts

I am working on inserting a list of topics with unique slugs into a MongoDB database. Here are two example topics: { title: "my title" }, { title: "my title" } After generating the slugs, I need to insert the topics: // Insert each topic async.map( ...

Is it feasible to fetch data from various keys in a single query?

I am currently in the process of searching for specific data within my database using a string, but I need to check multiple json keys. While I know how to search using a single key such as 'name', my challenge arises because I have two differen ...