从数组到变量名

时间:2017-04-27 21:04:18

标签: javascript arrays json

我正在抓取一个元素ID列表。

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

返回类似的内容:

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

对于数组中的每个项目,我想获取一些JSON数据。

        $.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);
        });

这样data.menu.list将为data.menu.lunchdata.menu.appetizers等。

JSON的结构如下:

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

任何不涉及eval()的想法?

编辑: 我什么时候这样做:

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

控制台告诉我:

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

我真正想要的是访问这些数组。

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

给了我一对未定义的东西。

5 个答案:

答案 0 :(得分:1)

如果您正在寻找将JSON字符串解析为对象,请转到:

&#13;
&#13;
var jsonString = '{"data":{"item":{"id":1,"value":"foo"}}}';
var jsonObj = JSON.parse(jsonString);
console.log(jsonObj.data.item.value);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

这是一个很棒的问题,先生!

无论您如何检索menusstrToVar()都会完成任务 此代码将字符串从数组转换为变量名称:

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]);

给我你所有的观点。

答案 2 :(得分:1)

问题是,我不明白我真正想做什么。我问了一个错误的问题(虽然它是一个有趣的问题,所以我会把它留下来。)

我认为我需要从HTML ID生成我的变量列表,但这是一个错误。我需要的只是另一个for循环(或jQuery each());

    $.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);
    });

答案 3 :(得分:0)

您的$.each功能应该是:

$.each(menus, function(i, list) { // the second parameter is list so we don't need menus[i]
    var meal = data.menu[list],   // use of bracket notation
        items = '<li><h3>' + meal.name + '</h3><p>' + meal.desc + '</p></li>';

    $('#' + list).append(items);
    //        ^^^ no need for the ".menu" as IDs alone are sufficient (assuming you have unique IDs, otherwise you have a problem)
});

MDN上的文档bracket notation

答案 4 :(得分:0)

根据我的理解,您希望实现类似

的目标

var menus = ["lunch", "appetizers", "soup", "salads"];
var menuList = [
                 {
                   "name":"lunch",
                   "description":"description1"
                 },
                 {
                   "name":"appetizers",
                   "description":"description2"                 
                 },
                 {
                   "name":"soup",
                   "description":"description3"                 
                 },
                 {
                   "name":"salads",
                   "description":"description4"                 
                 }
               ]
var menu = {};

for(var i in menus) {
  menu[menus[i]] = [{
      "name": menuList[i].name,
      "desc": menuList[i].description
  }];
}

console.log(menu);