What is the process for building a JSON-formatted dictionary?

My intention is to structure my data in a way that can be accessed using a specific key. The current arrangement looks like this:

    const dict = [];
    dict.push({"student": "Brian", "id":"01", "grade":"Sophomore"})
    return dict; 

Current Output:

{
      "student":"Brian"
      "id": "01",
      "grade": "Sophomore"
}


However, I am aiming to reformat my data structure to achieve the following:

{
  "student":"Brian" [ 

 { 
    "id":"01", 
    "grade": "Sophomore" 
 }

  ]
}

How can I accomplish this? My goal is to utilize "student" as the key to access the additional information tied to it.

Answer №1

Just a little tweak and you're almost there. When creating objects, remember to assign keys along with the values.

const dictionary = [];
dictionary.push({
  "Brian": {
    "id": "01",
    "grade": "Sophomore"
  }
})
// To retrieve: 
let brian = dictionary.filter(e=>Object.keys(e)[0]==="Brian").flatMap(Object.values)
if (brian && brian.length>0) console.log(brian[0])

// Alternatively, set up your `dictionary` like this:

const dictionary2 = {};
dictionary2["Brian"] = {
  "id": "01",
  "grade": "Sophomore"
};

// This way, you can easily retrieve your object using

brian = dictionary2.Brian;
console.log(brian)

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 failure of the ajax call to encapsulate is likely due to issues with object visibility

Having some trouble with a piece of code meant to run smoothly on Firefox 3.6. The issue arises when the variable this.xmlhttp, defined in STEP2 and used in STEP3, seems to be operating in different variable environments. Even though I expect the two usa ...

jQuery not refreshing properly

I'm currently in the process of creating a script to switch the language on a website using PHP and Ajax/jQuery. I would like the page content to refresh without having to reload the entire page. So far, this is what I have come up with: $( "a[data-r ...

Node.js & Express: Bizarre file routes

It's quite strange how my local paths are functioning. Let me show you an example of my directory structure: public > css > bootstrap.css public > js > bootstrap.js templates > layout > page.ejs (default template for any page) tem ...

Modify the length of an array using a number input field

Currently, I am working with an array that contains objects and I want to dynamically change the number of objects in this array based on user input from a number type input box. Whenever the number in the input box is increased, I need to increase the len ...

How to change the color of a row in Jquery selectize using its unique identifier

Is it possible to assign different row colors for each value in the jquery selectize plugin? I would like to set the row color to green if the ID is 1 and red if the ID is 0. This is my selectized field: var $select = $('#create_site').selecti ...

Display information in a div container from other pages on the website

I am attempting to dynamically load content into a div in Index based on the selection made in a dropdown box, but it doesn't seem to be working correctly. I have created a simple example using four pages to demonstrate the issue: Index.html one.html ...

Is there a way to retrieve SQL information through an API and then incorporate that data into react-native-svg charts? I have an API that contains data I would like to retrieve and showcase

I am utilizing an API to retrieve data, which includes the execution of SQL queries. The API is responsible for fetching data and running these queries. I am looking for a way to replace the static data in my charts with dynamic data fetched from the API. ...

Angular and JavaScript: Today is Monday and the date is exactly one week old

I am currently working on an Angular application that is connected to a REST API. In order to minimize the number of requests made, I have implemented a method to store all data in the local storage. .factory('$localstorage', ['$window&apos ...

The Facebook bots are unable to crawl our AngularJS application because the JavaScript is not being properly

I have a unique setup where my website is built with AngularJS and Wordpress as a single page application. Depending on the routing of the page, I dynamically define meta tags in the controller. Here's a snippet of my HTML header: <meta property=" ...

Using space as a separator for thousands when formatting integers

In an attempt to change the appearance of 1000 to resemble 10 000, I found numerous examples online on how to add a separator such as a comma or some StringLocal. However, I am looking for a way to use a space instead. Can anyone advise me on which locale ...

PHP Quick Tip: How to effortlessly update a JSON array with new data

{ "messages": [ { "sender": "x", "message": "Placeholder", "date": "May 8, 2016 11:47:45 PM" } { "sender": "y", "mess ...

Placing a cookie using nookies within the Next.js API directory

I'm currently facing an issue while trying to use the nookies npm package to set a cookie within the Next.js api folder. I've successfully set up a cookie using the same code with nookies before, but for some reason, it's not working in this ...

What exactly do `dispatch` and `commit` represent in vuex?

Recently, I came across a Typescript project in Vue.js with a Vuex store that had the following code: async getUserProfile ({ dispatch, commit }: any) {} I found working with any cumbersome as it doesn't provide helpful autocomplete features in the ...

Completion of the form within the Bootstrap popover

I have a feature where dynamically created rows contain an "add" button. When the user clicks on the add button, a form is loaded into a Bootstrap popover. See FIDDLE DEMO My issue is: Why isn't this code being triggered? I am trying to validate ...

There is no result being returned by Model.findOne()

Why does Model.findOne() return null even when a valid collection is present in the respective Model? app.post("/fleetManagement", (req, res) => { const requestedDriverID = req.body.driverId; console.log(requestedDriver ...

Sending properties within components using #createElement in React-Router is a convenient way to pass data locally

Have you ever wondered where the parameters Component and props are coming from in the React-Router documentation? // Here is the default behavior function createElement(Component, props) { // ensure all props are passed in! return <Component {... ...

Obtain an array as the response from an Ajax call

When passing data using Ajax request, I utilize the code below: var query = { "username" : $('#username').val(), "email" : $('#email').val(), } $.ajax({ type : "POST", url : "system/process_registration.php", ...

The challenge of maintaining coherence in AngularJS scopes

It's driving me crazy. Our integration with some ATSs involves sending queries and setting variables in the scope upon receiving responses. I always make sure to set the variables within a $scope.$apply() to ensure proper updating. Everything was work ...

The process of updating a nested object property in Redux and React

Initially, the user object is established with properties such as name, color, and age using the SET_USER method. I need to modify the name property within the user object utilizing UPDATE_USER_NAME. However, despite trying a nested loop within UPDATE_USER ...

What causes the website to malfunction when I refresh the page?

I utilized a Fuse template to construct my angular project. However, upon reloading the page, I encountered broken website elements. The error message displayed is as follows: Server Error 404 - File or directory not found. The resource you are looking fo ...