Unable to retrieve array element using named key in JavaScript

I am having trouble passing an array of objects to a php page within a larger data structure. My JavaScript code is attempting to replicate this structure and pass it via json.

In the php script, the array keys have been set as names that I will need later in the process.

Although JavaScript does not use associated arrays, arrays can be treated as objects. The documentation suggests that named keys can still be used.

It seems that I should also be able to use variables as named keys with a different syntax. Can someone help me identify what mistake I may be making?

Example 1: Using numeric keys (works)

var dataTargets = [];
var obj = {
  'test': 'test'
};
dataTargets["0"] = obj;
alert(JSON.stringify(dataTargets));

Example 2: Using named keys (fails)

var dataTargets = [];
var obj = {
  'test': 'test'
};
dataTargets["test"] = obj;
alert(JSON.stringify(dataTargets));
//outputs []

Example 3: Using variable keys (fails)

var dataTargets = [];
var dtname = "test";
var obj = {
  'test': 'test'
};
dataTargets[dtname] = obj;
alert(JSON.stringify(dataTargets));
//outputs []

Answer №1

The issue lies in how JSON.stringify treats arrays by ignoring non-index properties, which causes the correct properties to not be displayed when stringifying the array. To resolve this, it's recommended to use plain objects {} instead of arrays [] if you want to assign named keys to your objects:

var alert = console.log.bind(console) // for demo purposes


// Example 1: numeric keys 

var  dataTargets = {};
var obj = {'test':'test'};
dataTargets["0"] = obj;
alert(JSON.stringify(dataTargets));


// Example 2: named keys

var  dataTargets = {};
var obj = {'test':'test'};
dataTargets["test"] = obj;
alert(JSON.stringify(dataTargets));


// Example 3: variable keys 

var  dataTargets = {};
var dtname = "test";
var obj = {'test':'test'};
dataTargets[dtname] = obj;
alert(JSON.stringify(dataTargets));
//outputs []

Answer №2

here is an example of how to approach this situation

Scenario 1:

var  dataTargets = [];
var obj = {'test':'test'};
dataTargets[0] = obj;
alert(JSON.stringify(dataTargets));
// displays [{test:test}]

to achieve the desired outcome, you should do the following:

var  dataTargets = {};
var obj = {'test':'test'};
dataTargets["test"] = obj;
alert(JSON.stringify(dataTargets));
//{"test":{{test:test}}}

the reason for this is that arrays are accessed by index, while objects can provide what you require

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

Ascending to the Peak within a div

<script type="text/javascript"> $(document).ready(function(){ updateContent(); }); function updateContent(){ $('#mainDiv').load('home.php', function(){ scrollToTop(); }); } ...

Having trouble with connecting to Gmail while using Nodemailer? Facing a Connection Timeout

Seeking assistance with sending emails through nodemailer. See below for the code snippet. var transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: '<<a href="/cdn-cgi/l/email-protecti ...

Antd 4: Updating the value in Form.List dynamically with setFieldsValue

<Form> <Form.List name="projects"> {fields => ... fields.map(field => <Form.Item name={[field.key, "type"]} hidden={true} initialValue={type} />) ... } </Form.List> </Form> ...

Dividing CSV Data into Two File Outputs

I've got a CSV file that's structured like this: Docushare Host locale, created_at, version en,Wed Feb 21 17:25:36 UTC 2018,07.00.00.C1.609 User handle, client_data, docCountQuota User-12,,-2 Document handle,client_data,cfSpecialWords Document ...

Selecting the textarea element within a form using jQuery

Here is a code snippet that I've been working with: <!DOCTYPE html> <html> <head> <meta http-equiv='Content-Type' content='text/html;charset=utf-8' /> <script type='text/javascript' sr ...

What are some effective methods for selectively handling batches of 5-20k document inputs when adding them to a collection containing up to one million documents using MongoDB and Mongoose?

My MMO census and character stats tracking application receives input batches containing up to 5-20k documents per user, which need to be aggregated into the database. I have specific criteria to determine whether a document from the input already exists i ...

Place the script tags within the window.load function inside the head section

<head> <script type="text/javascript"> $(window).load(function() { // <script src="js/external.js"></script> // }); </script> </head> Is it possible to insert a script tag(< script src="js/exte ...

Accessing the Angular scope and making modifications using Chrome browser

I need to access the $scope value in order to update its data values via a chrome extension. I have attempted to obtain the $scope using the code below: var $scope = angular.element(document.getElementById('name')).scope() While this code wor ...

a guide on configuring a default input value from a database in a React component

In my current project, I have an input field with the type of "checkout" and I am looking to utilize Firestore to retrieve a default value. Once I obtain this value, I plan to store it in the state so that it can be modified and updated as needed. Here i ...

Node.js MongoDB Error: db.open is undefined

I recently started experimenting with MongoDB and encountered an error message stating TypeError: db.open is not a function. Although new mongodb.Server and new mongodb.Db seem to be functioning correctly. The issue arises while using [email protecte ...

Uncovering the Model within a controller in Ember JS

I am attempting to extract the original model object from a controller for the purpose of persistence (without utilizing ember-data). The straightforward approach would be: controller.get('content'); However, this method is not effective. The i ...

Is it viable to create an onClick event for the text content within a text area?

I'm working on a project that involves displaying XML data in a textarea and creating an onClick event for the content within the textarea. For example: <textarea>Hello Web, This is a simple HTML page.</textarea> My goal here is to cre ...

Extract the value of an HTML tag and store it in a PHP variable

I have successfully implemented JavaScript code to dynamically update the value of an input tag in my popup. However, when I try to echo out this updated value using a PHP variable within the same popup, it doesn't seem to work as expected. Despite un ...

Determine the RGB color values for specific coordinates within Adobe Illustrator

Currently exploring ExtendScript for JavaScript in Adobe Illustrator 2015. Is there a method to retrieve RGB values based on coordinates within the code below? // initializing document var doc = app.activeDocument; // defining x and y coordinates for colo ...

What is the best way to distinguish between enabled buttons using Protractor?

I am facing a challenge with a table containing 20 buttons. Half of these buttons are disabled while the other half is enabled. I am looking for a way to filter out the enabled buttons and click on each of them using a for loop. The buttons that I want to ...

Unlocking the power of ReactJS: Utilizing context in the parent component

I am currently working on developing a foundational component that can manage UI themes. The theme is supposed to be passed to components through context, but I'm encountering an issue where the base component I've built does not seem to receive ...

What is the best way to switch to a new HTML page without causing a page refresh or altering the URL?

Is there a way to dynamically load an HTML page without refreshing the page or altering its URL? For instance, if I am currently on the http://localhost/sample/home page and I want to switch to the contact us section by clicking on a link, is it possible t ...

Is it possible to instantiate a Backbone view by referencing its string name that is stored within a JavaScript object?

I am currently working on a visual builder that utilizes different views for each component. Each view is defined as shown below: $(function() { var parallaxView = new Backbone.view.extend({ .... }); var parallaxView = new Backbone.view.e ...

Utilizing ckeditor's extraAllowedContent attribute for the viewhelper functionality

Is it possible to incorporate content for my php FormViewHelper method? The syntax is @form('inputName')@, which assigns a value to the input field if provided and the form has not been successfully submitted yet. I am developing a specialized ...

Arranging items by their total sum of arrays in React.js

I'm working with data.js where I have stored my JSON information. Here's a snippet: [ { name: 'Adam Doe', city: 'New York', mark: [8,10,10,10] }, { name: 'Catlyn Stronk', ...