Create an array containing key-value pairs where the values are objects

I've been struggling to create a specific data structure in Javascript and I could really use some guidance:

[arrayValue: {objectKey: objectValue}, arrayValue2: {objectKey: objectValue}]

Here's what I've attempted so far:

var arr = [];
var obj = {};

var name = "Test";
var password = 'password';
var value = 'value'

obj[name] = {name: name, value: value, password: password};

arr.push(obj);

I'm using this method of pushing data to an array because I have a dataset that requires multiple iterations.

Unfortunately, the results are not as expected:

[{"Test":{"name":"Test","value":"value","password":"password"}}, {"Test2":{"name":"Test","value":"value","password":"password"}}]

My intended format is:

["Test":{"name":"Test","value":"value","password":"password"}, "Test2":{"name":"Test","value":"value","password":"password"}]

This way, I can access array objects by their names like arr[Test].name instead of arr[0].name

Any help on this would be greatly appreciated. Thank you!

Answer №1

Arrays do not support named objects, meaning you cannot access a specific element in an array using syntax like array['Test']. Objects inside an array can only be accessed using indices (indexes). Therefore, if you need to include an object in an array, you must retrieve it by its index. Your intended construction syntax is incorrect.

However, if your goal is not to iterate through the array but simply to retrieve specific items by their names, consider placing each object within a "container" object instead.

Answer №2

Arrays do not have specific keys; they are only indexed by numbers. If you want to access a specific value based on a key, you should use objects and the syntax obj[variable].

var obj = {One: 1, Two: 2, Three: 3}
var num = "Three"
console.log(obj[num]);

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

Cease the cropping function for Cropper.js when it extends beyond the boundaries of

Is there a way to prevent the crop corners from moving once the user drags the cursor out of the image while cropping? I encountered an issue where the cropped corners are displaced from the cursor when the user moves out of the image and then back in, wh ...

Encountering the issue of receiving an "undefined" object while trying to parse JSON

Trying to extract data from the AccuWeather API using a Node.js application. I managed to parse the response using the JSON.parse() method. However, when attempting to access certain nested objects, I encounter an undefined value. Being relatively new to t ...

Creating a seamless scrolling experience with a designated stopping point - here's how to achieve it!

I understand how to implement a scroll effect on an element with a specific class or ID. However, I am unsure of how to make the scrolling stop 20px above that element. I have seen examples using document.getElementById() to achieve this: function scr ...

When the value is removed, it does not revert back to the initial filtered choices

After clearing the input, I want to display all the original li's again. The issue is that even though .value = '' clears the input, the filter remains active. I could really use some help with this as it's starting to get on my nerves ...

Force a video element to play by using React Context Provider

I've been incorporating the React Context in a similar manner here, and I'm facing a challenge on how to update my video element (to play the video). Shouldn't the components automatically update when they receive the prop? Below is a simpl ...

Ways to insert a color into an HTML text box based on a condition

Hey everyone, I need some help with changing the color of a textbox in cshtml. Here is the code snippet I am working with: $("#BUTTON").click(function (event) { var urlPA = URL; var crty = $("#Courtesy").val(); var fname = $("#Familyname").val ...

Ways to navigate back to the previous ajax request

I am currently working on a script that involves numerous ajax requests. The script is functioning well, and it features dynamic content that changes based on user selections or search inputs. I have been exploring how to manipulate the browser history in ...

Navigating nested loops within multidimensional arrays

Currently, I am experimenting with nested loops to search through nested arrays in order to find a specific value called "codItem". Below is a test model for the array (as I do not have access to the original fetch request on weekends): let teste = [{ it ...

Guide on creating a JSONP request

My goal is to perform cross-site scripting. The code snippet below shows the jsonp method, which appears to fail initially but succeeds when switched to a get request. I am trying to achieve a successful response using the jsonp method. I have confirmed th ...

Is there a way to prevent the use of angular.reloadWithDebugInfo() in the browser console?

Is there a way to secure app scope variables from being accessed through the browser console? I've already disabled debug info using $compileProvider.debugInfoEnabled(false); But it seems like this setting can still be bypassed with reloadWithDebugIn ...

Discovering the parent route details of the current route from within a component

I am facing an issue where I need to identify the parent route /products while working within the scope of the FeaturedProducts.vue component. The current route path for this component is set as /product-list/featured const routes = [ { path: "/ ...

Is my configuration file causing Express to serve up index.html instead of my Webpack bundle?

My website is having trouble loading because instead of the bundle.js file, it's returning the index.html file. This project was originally created a few years ago and worked without any issues. However, I'm currently trying to revive it and enc ...

Creating a large array of functions can be done by defining each function within the array individually, ensuring proper

I attempted to define an array of functions using the code below, but encountered issues with retrieving the value of 'i' outside of the loop. <script> var f = [] for (var i=0; i<1000; i++){ f[i] = function(){ return i } ...

Creating a file by piping the output of an asynchronous HTTP request while utilizing async await method

I have been diligently following the instructions and conducting thorough research for a whole day to figure out how to use a pipe to compile an Excel spreadsheet that is fetched through an API call. I managed to get part of the way in saving it, but unfor ...

What is the most effective method for dividing a string in TypeScript?

Here is the scenario: receiving a string input that looks like Input text: string = "today lunch 200 #hotelname" Output subject: "today lunch" price: 200 tag: #hotelname My initial solution looks like this: text: string = "today lunch 200 #hotelname" ...

Struggling with making an Ajax and Jquery drop down menu work? Wondering how to use Javascript to retrieve a variable and then utilize it in PHP? Let's troubleshoot

Currently, I am utilizing Ajax/Jquery to present a dropdown menu with data retrieved from my SQL database. The process involves using javascript to obtain a variable that is then utilized in PHP. However, the function doesn't seem to be working as exp ...

The array becomes empty after a value has been assigned to it

I am currently working with a variable containing JSON data. var blogData = [ { "blogTitle":"Bangladesh", "imagePath":"/img/blog/bangladesh.jpg" },{ "blogTitle":"In ...

Is there a way to transform a string that holds an array into an actual Array utilizing Javascript?

I have a string that looks like this: '[a, b]' I am looking to create an array that appears as follows: ["a", "b"] This is the script I came up with: const str = '[a, b]' const arr = str.replace('[', '').replace( ...

What is the correct way to establish the value of an editable div element?

When working with input and other elements that have a value, I usually use Object.getOwnPropertyDescriptor(input, 'value').set; followed by element.dispatchEvent(new Event('input', {bubbles: true})). However, this approach does not wor ...

The dropdown menu repeatedly opens the initial menu only

My script fetches data from a database to populate a table with one row for each member. Each row contains a dropdown list with the same class and ID. Although I attempted to open and close the dropdowns using specific codes, I am facing an issue where onl ...