Get the name of the array using JavaScript

Here is an example of my situation:

var list1 = ['apple', 'banana', 'orange'];

var list2 = ['carrot', 'lettuce', 'tomato'];

When I use:

alert(list1) I get: apple, banana, orange. This is correct.

Now, I want to get the name of the array from a different function. In this function, I loop through an array like this:

var allLists = [list1, list2]

for (i = 0; i < allLists.length; i++) {
  alert(allLists[i]);
}

Currently, I see "apple, banana, orange" followed by "carrot, lettuce, tomato" in the alerts. What I actually want is to display the names of the arrays, not their contents. How can I achieve this?

My goal is to have two alerts showing: "list1" and "list2", the names of the arrays.

Answer №1

Store your arrays inside an object:

var obj = {
    first: ['15','30','45'],
    second: ['5','10','15']
}

for (var key in obj) {
  console.log(key); // display the key
}

Alternatively, you can use Object.keys(obj) to get an array of the object's keys.

If you want to display the array contents:

for (var key in obj) {
  console.log(obj[key]); // show the array contents
}

DEMO

Answer №2

Absolutely, I concur with elad.chen's suggestion. Here is an alternative approach you could consider:

let items = [
    {label:"first",options:['A','B','C']},
    {label:"second",options:['D','E','F']}
];

for(let j=0;j<items.length;j++){
    console.log(items[j].label); 
    console.log(items[j].options); 
}

Answer №3

To create an "Object Literal," assign the property name as the key and the corresponding array as the value.

For demonstration purposes:

var items = {
"first": [5,6,7],
"second": [5,6,7]
}

for ( var key in items ) {
  alert('Key = ' + key)
  alert('Value = ' + items[key].toString() )
}

Answer №4

It is important to assign a name somewhere in the code. Although JavaScript allows adding properties to objects, this feature can be utilized to assign a name property without impacting the behavior of arrays.

var first = ['12', '24', '36'];
first.name = 'first';
var second = ['10', '20', '30'];
second.name = 'second';
var example = [first, second], index;

for (index in example) {
    document.write(example[index].name + '<br>');
}

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

Duplicate multiple "li" elements using jQuery and place them in a designated position within the ul element, rather than at the end

I am currently working on developing a dynamic pagination bar. This pagination bar will dynamically clone the "li" elements based on a number received from an external webservice. Here is the structure of my pagination element: <ul class="pagination"& ...

What's the best way to showcase data in a column dynamically depending on its specific columns?

I have an array of objects representing columns and another array representing table data. I need to dynamically display the data in the specified columns. Some objects have 3 key-values which should be displayed in specific columns. The second object in ...

Using jQuery to fetch data asynchronously

I am currently dealing with a web application that needs to carry out the following task. It must send GET requests to a web service for each date within a selected date range, yet this process can be time-consuming. Since I plan to visualize the retrieved ...

Using a combination of Vue.js and AJAX to make requests within a v-for loop, all while

I have a set of data (todos array) that displays in my model, and I am rendering this data in a list. I am trying to implement a functionality on the list that whenever click on any item on the list, the selected variable's value should be updated wi ...

Fetching information with request query parameters in Node.js

Working on implementing email verification using nodemailer for user sign-ups. The process involves sending out an email containing a link (usually something like localhost:3000/verify/?id=##). After the user clicks the link, I can see that a GET request ...

Display a collection of objects using Jade / Pug syntax

Struggling to find resources on Pug / Jade templating, turning to this platform for help. I've been diving into documentation on iterations along with consulting this helpful link. Working with Node.js, Express, and pug for a school project - a mock ...

How do you go about installing the most recent version of a module through Private NPM?

When using a private npm registry, I have noticed that some common commands do not seem to be functioning properly: npm install without specifying a specific @version :: issue npm outdated :: issue npm update :: issue npm view <private-packag ...

error": "message": "Property 'name' cannot be read because it is undefined

I've encountered an issue while creating a route to handle POST data. Despite testing it on postman, I have not been able to find a solution for the problem that many others seem to be facing as well. It seems like the 'name' field is not be ...

Is there a way for mocha to conduct a recursive search within my `src` directory in order to find a specific

In my npm project, I want to replicate the structure used by Meteor: there is a source file called client.js and its corresponding test file named client.tests.js residing in the src/ directory. The tests should be executed with the npm test command. I am ...

An interactive 3D model emerges against a sleek ebony backdrop on my online platform

I stumbled upon a three.js 3D object featuring a unique touch - a 404 text with a floating orb replacing the zero. Upon importing its code, it rendered successfully, albeit against a black background. Despite my efforts to tweak values and apply background ...

Add the item and increase its value within an array using AngularJS

http://plnkr.co/edit/NDTgTaTO1xT7bLS1FALN?p=preview <button ng-click="addRow()">add row</button> <div ng-repeat="row in rows"> <input type="text" placeholder="name"><input type="tel" placeholder="tel"> </div> I am cur ...

Using JavaScript, adding an element to an array results in the array returning a value of 1

When I try to push a string into an array and then return the array, I am getting unexpected result of "1". Upon closer inspection, it seems that the array is being successfully created but before returning it, only "1" is being returned. Here is the snip ...

Modify the css of the initial div following a live click

After clicking on the span.submit-comment, I am looking to modify the CSS of a specific div. Can anyone advise me on how to achieve this? I attempted to change the background color of the div in the success section of the script like so: $('div.new ...

I'm seeking assistance with a frontend script problem. I'm curious if there are alternative approaches to coding this script that may be more effective. Can anyone offer guidance on this?

As a frontend developer specializing in script injection, I have been utilizing Adobe Target to inject scripts. However, this method presents several challenges: 1. It is difficult to debug code errors as my HTML and CSS are wrapped inside ' ' a ...

Experience the power of TypeScript in a serverless environment as you transform your code from

I have some JavaScript code that needs to be converted to TypeScript. Currently, I have two files: API_Responses.js const Responses = { _200(data = {}) { return { statusCode: 200, body: JSON.stringify(data), }; } }; module.export ...

Preserve the JavaScript Promise for later utilization

While experimenting with Node.js to construct the server side RESTApi, I encountered a situation where it functioned effectively during my independent tests. However, once deployed in a live environment, issues related to overflow arose. Specifically, when ...

tips for navigating through an AngularJS $resource instance

I am facing a frustrating issue that I need assistance with. The problem arises when I try to extract specific data from each element of the stock data fetched by my controller from Yahoo Stocks. Although the data is stored in $scope.stocks and can be disp ...

Burst forth with unexpected and random elements within an array

How can we explode all the child tags innerHTML while preserving the order of their occurrence? The set of tags below is random and unpredictable, wrapped inside a div tag. Note: For img and iframe tags, only the urls need to be extracted. <div> ...

Executing Selenium WebDriver to interact with a hidden element

Hello, I am interested in learning how to interact with hidden elements and disable them using Selenium WebDriver. I've managed to achieve this with Selenium 1 by using the following code: selenium.click(id="idOfHiddenField"); Unfortunately, this a ...

What is the method for obtaining the most up-to-date JSON GET request URL?

Using JQGrid with search filters and setting loadOnce=false. I perform a search in the grid and observe the JSON request URL in firebug: http://localhost:8080/myapp/items/listGrid?ticketId=&_search=true&nd=1393573713370&rows=20&page=1& ...