Including the names of elements in a nested object

Below is a list of variables I have:

var test = [{…}, {…}, {…}]

I want to assign names to each element so that I can access them using test.grade, test.name, and test.area. While I can think of a basic way to add names to each index, I am curious about the most elegant approach to achieve this.

 var columns = //
    var a= {};
    var b= {};
    var c= {};

    for(var i =0; i< columns.length; i++){
      a[columns[i]] = this.geta[i];
      b[columns[i]] = this.getb[i];
      c[columns[i]] = this.getc[i];

    }

    var test = [];
    var Name0 = "name";
    var Name1 = "grade";
    var Name2 = "area";

    test.push(a,b,c);

//test = [{name: Mike, grade: 10}}, {name: Sarah, grade:25}},{name:chris, grade:0}}]

This is the desired format:

[{A: {name: Mike, grade: 10}}, {B:{name: Sarah, grade:25}}, {C: {name:chris, grade:0}}]

After formatting like this, my goal is to access elements by names such as res.A.name or res.B.grade...

Answer №1

If you wish to retrieve something using dot notation, it must be stored as an object.

test.push({
   grade:"grade",
   person:"person",
   area:"area"
});

After that, you can access the elements of the test array and properties of each element like this:

test[0].person;
test[0].grade;
test[0].area;

UPDATE: stored as an object

test={};
test['Name0']={person:"person1",grade:1,area:"..."};
test['Name1']={person:"person2",grade:1,area:"..."};
test['Name2']={person:"person3",grade:1,area:"..."};

You can then access them like this:

test.Name0.person

You can choose any name to use,as it is a string so you can use for/foreach loops for iteration.

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

When executing a dispatch in Redux, an error message is returned indicating that 'action' is not defined

I'm new to using redux and I am currently creating a todo list with redux. Here is a snippet of my action creator code: /** * This file is called Action Creator (creates actions) * * Actions are objects like: * { * type : 'ADD_TODO&a ...

What is the best way to swap the values of options between two input select elements?

I am trying to create a feature where I have two select dropdowns with the same options, and when a trigger is clicked, the option values are inverted between the two selects. Here is an example: <select id="source_currency"> <option value="BRL" ...

Why do certain URLs bypass the filters despite not meeting the criteria in the Chrome extension?

I am currently developing a Chrome extension that is designed to automatically close tabs when specific URLs are visited, helping me stay focused and avoid distractions. The list of sites that should trigger tab closures includes: YouTube Facebook Reddit ...

Leveraging jQuery with PHP's POST method

I have limited knowledge in jquery and ajax, but I am in need of a specific functionality on my website. Once users log in successfully, they should be able to download PDF files from the page. There is a collapsible div where users can select which file ...

What is the most efficient way to optimize the time complexity of a JSON structure?

Here is the input JSON: const data = { "38931": [{ "userT": "z", "personId": 13424, "user": { "id": 38931, "email": "sample", }, } ...

Invoke a JavaScript function once the div has finished loading

After clicking on a radio button, I am dynamically loading a div element. I want to hide a specific part of the div once it is loaded. $(function($) { $('.div_element').on('load', function() { $('.textbox').hide(); } ...

Ways to retrieve the value of a variable beyond its scope while using snapshot.foreach

I am experiencing an issue where the return statement returns a null value outside the foreach loop of the variable. I understand that the foreach loop creates its own scope, but I need to figure out how to return the value properly... this.selectedUserMe ...

Which NPM packages are necessary for implementing modular Vue components?

While I have experience with traditional multi-page applications created using HTML + JS libraries and server-side rendering (SSR), I am relatively new to modern web development. Currently, I am learning Vue JS (the latest version) through online tutorials ...

Retrieving POST Data in PHP from Ajax with Dual Conditions

Let's say I have two textboxes, one named serial_no10 and the other named serial_no12. These textboxes may or may not appear at the same time depending on the situation. Additionally, there is a PHP file used to check the serial numbers and a div elem ...

The Slider component in Material UI's API may not properly render when using decimal numbers as steps or marks in React

I am having trouble creating a Material UI slider in my React application. I can't figure out which property is missing. Below is the code for my React component: import * as React from 'react'; import Slider from '@material-ui/core/S ...

What causes the JavaScript function to have an undefined return value?

I have written a function that is designed to determine the size of an image and return an object containing both the width and height. However, I am encountering an issue where the values for sz.width and sz.height are defined within the function but beco ...

Utilize React Material UI to elegantly envelop your TableRows

Currently, I am faced with a challenge involving a table that utilizes Material UI and React-table. My goal is to wrap text within the TableRow element, but all my attempts have not been successful so far. Is there anyone who knows the best approach to a ...

Is it possible for me to access information from an external URL using JSON?

As I delve into learning about JSON for app development, I've encountered an issue with a JSON and PHP-based chat system. While the code functions properly for the same origin policy, when it comes to sending and receiving data from an external URL, i ...

You cannot nest a map function within another map function in React

Having some trouble applying the map function in HTML using React. Below is the code snippet: response = [ data : { name: 'john', title: 'john doe', images: { slider: { desktop: 'link1', mo ...

Encountering a Cannot GET error when using Express routing with parameters:

I've encountered a "Cannot GET" error while attempting to use express routing with parameters for the first time, and I'm puzzled as to why. Everything was working smoothly until I installed lodash, and now nothing seems to work anymore. Here&a ...

Tips on transferring information from a component to an instance in Vue

My goal is to retrieve data from a component and transfer it to a variable within my root Vue instance. Vue Instance Configuration: new Vue({ el: '#root', data: { searchResultObject: '' }, methods: { // ...

Creating dynamic HTML elements can be achieved by using JavaScript to dynamically generate and

I have an array var elements = ["What?", "How", "Who", ......]; My goal is to generate the following components: <html .. whatever> <div id="q1"> What? </div> <input type="text" id="a1"></input> <div id="q2"> How ...

Populating a Div with Information

I'm currently working on a project where I have a div with predefined dimensions, but the content inside is set to not display initially. Above this div, there are several p tags that act as clickable links to reveal different content within the div ...

Is there a way to determine if an iframe has finished expanding?

I have a contenteditable iframe that can be resized so that not all of its contents are visible. What is the best way to determine if this iframe is fully expanded or not? ...

How can I terminate a parent function in NodeJS when inside a virtual function?

Here is something similar to the code snippet below: var async = require(async) function start () { async.series( [ function (callback) { // do something callback(null, "Done doing something") ...