assigning array strings to a variable

Assembling a collection of element IDs like this:

var menus = $(".menu").map(function(){
            return this.id;
        });

The result might look something like this:

["lunch", "appetizers", "soup", "salads", "seafood", "noodles", "stir_fry", "curry", "kids", "steak", "dessert", "sides"]

My goal is to retrieve JSON data for each item in the array.

        $.each(menus,function(i) {
            var list = menus[i],
            meal = data.menu.list,
            items = '<li><h3>' + meal.name + '</h3><p>' + meal.desc + '</p></li>';

            $('#'+list+".menu").append(items);
        });

In this scenario, data.menu.list represents data.menu.lunch, data.menu.appetizers, and so forth.

The JSON structure is as follows:

{
    "menu": {
        "lunch": [{
            "name": "Kao PAdd",
            "desc": "Fried rice with onions, green onions, snow peas, and egg / Chicken, vegetarian / Shrimp or tofu (Add $1)"
        }

Any ideas on how to proceed without resorting to eval()?

EDIT: When I execute this code:

$.each(data.menu,function(i) {
    console.log(data.menu[i].key);
});

I receive the following output in the console:

Object {lunch: Array(14), appetizer: Array(11)}

All I want to do is access those arrays.

console.log(data.menu[i].name)

This returns a pair of undefined values.

Answer №1

Wow, what an excellent query, my good Sir!

Regardless of how you fetch your menus, the function strToVar() is up to the challenge.
This snippet of code transforms strings from an array into variable names:

Solution:
    var strToVar = (str,val) => this[str] = val;

Example:
    var menus = ["lunch", "appetizers", "soup", "salads", "seafood", "noodles", 
        "stir_fry", "curry", "kids", "steak", "dessert", "sides"];
    menus.forEach(strToVar);
    prompt("[lunch, appetizers, soup, salads, seafood, noodles, " +
        "stir_fry, curry, kids, steak, dessert, sides]", 
        [lunch, appetizers, soup, salads, seafood, noodles, 
        stir_fry, curry, kids, steak, dessert, sides]);

All your points belong to me.

Answer №2

For those interested in converting a JSON string into an object, check out this code snippet:

var jsonStr = '{"data":{"item":{"id":1,"value":"bar"}}}';
var jsonObject = JSON.parse(jsonStr);
console.log(jsonObject.data.item.value);

Answer №3

The challenge lay in my lack of clarity regarding my true objectives. I found myself posing the wrong question (albeit an intriguing one, so I will preserve it for now).

Initially, I mistakenly believed that I needed to derive my variable list based on HTML IDs. However, I eventually realized that a simple additional for loop (or jQuery each()) was all that was required:

    $.each(data.menu, function(i) {
        var list = data.menu[i],
            menus = [];
        $.each(list, function(x) {
            var items = '<li><h3>' + list[x].name + '</h3><p>' + list[x].desc + '</p></li>';

            menus.push(items)
        });
        $('#' + i).append(menus);
    });

Answer №4

Here is your updated $.each function:

$.each(menus, function(i, list) {
    var meal = data.menu[list],
        items = '<li><h3>' + meal.name + '</h3><p>' + meal.desc + '</p></li>';

    $('#' + list).append(items);
});

If you need more information on bracket notation, check out the MDN documentation here.

Answer №5

Based on my comprehension, it seems you are aiming to achieve a functionality similar to the following :

var meals = ["breakfast", "brunch", "lunch", "dinner"];
var mealList = [
                 {
                   "name":"breakfast",
                   "description":"morning delights"
                 },
                 {
                   "name":"brunch",
                   "description":"late morning feast"                 
                 },
                 {
                   "name":"lunch",
                   "description":"afternoon nourishment"                 
                 },
                 {
                   "name":"dinner",
                   "description":"evening satisfaction"                 
                 }
               ]
var meal = {};

for(var i in meals) {
  meal[meals[i]] = [{
      "label": mealList[i].name,
      "info": mealList[i].description
  }];
}

console.log(meal);

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

Methods for reducing arrays in JavaScript

Is there a way to transform an array of objects into an object with one of the properties as a key? What is the best method to achieve this conversion? const data = [ { id: "first", name: "Product 1", type: "selecti ...

When the same component is conditionally rendered, it does not activate the mounted() hook

I am new to Vue and eager to learn. I am attempting to conditionally render a component like so: <div> <Map v-if="bool" mapSrc="src1.jpg" :idList="idList1" :data="dataVariable1"></Map> <Map v-else mapSrc="src2.jpg" :idList="idList ...

Identifying memory leaks in Javascript

I've developed a basic script to retrieve the size of a list in redis and display memory usage. It appears that the amount of "heap used" memory is gradually increasing. Could this indicate a memory leak, and what modifications can be made to preven ...

Accessing JavaScript results in PHP

Hello everyone! I am working on creating a dropdown menu for selecting time using JavaScript to get the computer's current time. My goal is to have an output that automatically selects the option in the dropdown if it matches the computer's time. ...

Unusual octal phenomenon

It has come to my understanding that in ECMAScript 5, octal literals (such as 023) are considered invalid although widely supported. However, ECMAScript 6 introduced support for them in the form of 0o23 or 0O23. What puzzles me is how numbers that are not ...

Make sure to validate onsubmit and submit the form using ajax - it's crucial

Seeking assistance for validating a form and sending it with AJAX. Validation without the use of ''onsubmit="return validateForm(this);"'' is not functioning properly. However, when the form is correct, it still sends the form (page r ...

Activate CSS3 Transform using a JavaScript button click

As a newcomer to CSS3 transitions, I am attempting to create an image slideshow specifically for webkit browsers. The setup involves three images aligned next to each other within a wide DIV container, which is nested inside another container with hidden o ...

Managing null values in a map using Jackson

HashMap testMap = new HashMap(); testMap.put("Key1", "Value1"); testMap.put("Key2", null); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enableDefaultTyping(); objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL,JsonTyp ...

Maintaining the generic types in mapped types in TypeScript

In my current project, I have a unique design where a class contains instance methods that act as handlers, each representing a specific operation. These handlers take a reference as input and assign the output to a second parameter. To simplify this proce ...

Utilize morris.js within an AngularJS directive to handle undefined data

Using the morris.js charts in my angular js app has been a great addition. I decided to convert it into a directive for better organization and functionality: barchart.js: angular.module('app_name').directive('barchart', function () ...

Having trouble accessing a two-dimensional array using pointers

Int arr[2][4], *p; p = &arr[0][0]; *(p + 2) = 10; //ok *(p + 5) = 20;// ok *(*(arr + 1) + 3) = 15;//ok *(*(p + 1) + 3) = 15;// error I'm puzzled as to why the last line gives me an error while the one just before it works perfectly fine. p i ...

How to toggle the visibility of an element in an array using AngularJS and JavaScript

Is there a way to show additional information when an item in ng-repeat is clicked, and then hide this extra info when the mouse leaves that same item? One issue I am facing with the code snippet below is that when a user clicks on a different item, it al ...

Troubleshooting Bootstrap 4's Multiple Sort Functionality in Tables

The Bootstrap Tables "Multiple Sort" plugin ("Multiple Sort"), specifically the showMultiSort feature, is currently not functioning properly with Bootstrap 4. The demonstration available on the linked page shows visible issues. While the button associated ...

How to extract user data from a JWT token using Node.js?

In my MEAN stack authentication application, I am utilizing Node and Angular. After a successful login, I set a JWT token and store it in a session within the controller by assigning the token to config.headers through a service interceptor: var token = j ...

Discovering the reverse order of an array in C++

Create a program that takes input of characters until the symbol * is reached. Utilize a function to display the sequence in reverse order, using arrays. I attempted this task but encountered an error: *** stack smashing detected ***: ./a.out terminated ...

JSON is functioning properly, however, I am encountering difficulties trying to make JSONP work

Hello, I have been working on trying to make some JSON work properly. Here is the code snippet that I have written: $.getJSON("/calendar/event/test", function(data) { $.each(data, function(i,item){ $('#test').append('<li>' ...

Creating a multidimensional JSON array using PHP

I'm struggling to create a JSON array from the JQuery UI map with a specific structure. {"markers":[{"latitude":57.7973333, "longitude":12.0502107}, {"latitude":57.6969943, "longitude":11.9865}]} At this point, I'm unsure of how to achieve this ...

Error encountered while trying to connect to WebSocket: InvalidStateError

After setting up a basic Vue project with the vue-cli tool using vue init webpack my-project, I encountered an issue with sending information through a web socket before the page renders. To keep this logic separate from the Vue component, I created a sepa ...

How many elements are in the string[] array?

After extensive research on Google, I have yet to find a solution for my issue. The challenge at hand involves reading a TextBox line by line. Currently, I am utilizing the following code: string[] lst = txt.Split(new Char[] { '\n', ' ...

Excel - Fetch data from an array

Within my company, there are specific excel functions that produce a large array containing over 2000 rows and multiple columns. Here is a generic example: {=FunctionThatReturnArray(param1)} where param1 represents the date I am looking to extract the ...