javascript - 如何从对象中检索数组

标签 javascript arrays json

我试图从对象中获取信息并将其放入函数中,但未成功。

附件是我的代码:我尝试连接的部分是 recipeType.ingredientsfunction getRecipeItems()

HTML 是最小的,所以我将只附加 JS。 当请求 recipeTypename 时,它工作得很好,但一旦我请求配料,它就丢失了。

JS

function getRecipeItems() {
    return recipeItems = [
        {
            "id": "recipe0",
            // ...
            "price": {
                default: 8,
                ampm: 10,
                // -- haCarmel: 12, -- Let's omit this one
                tivTaam: 15,
                get: function( merchant ) {
                    return this[merchant] ? this[merchant] : this.default;
                }
            }
        }
    ]
}

function getMerchantprices() {
    return Merchantprices = [

        {
            "Booz": {
                ampm: 10,
                haCarmel: 23,
                tivTaam: 35,
                get: function (ingredient) {
                    return this[ingredient] ? this[ingredient] : 0;
                }
            }
        },
        {
            "Roofis": {
                ampm: 10,
                haCarmel: 23,
                tivTaam: 35,
                get: function (ingredient) {
                    return this[ingredient] ? this[ingredient] : 0;
                }
            }
        },
        {
            "Green Stuff": {
                ampm: 10,
                haCarmel: 23,
                tivTaam: 35,
                get: function (ingredient) {
                    return this[ingredient] ? this[ingredient] : 0;
                }
            }
        }
    ];
}

var main = function () {

    var recipeType = {
        0: {"name": "cocktail",
            "ingredients": [{"name":"Booz","price":10},//shouldn't this be merchantPrices.Booz?//
                            {"name":"Roofis","price":23},
                            {"name":"Green Stuff","price":8}]},

        1: {"name": "appetizer",
            "ingredients": [{"name":"Some leaves","price":7},
                            {"name":"Some veggies","price":17},
                            {"name":"I dunno toast","price":10},
                            {"name":"Cheese or whatever","price":17}]},

        2: {"name": "main course",
            "ingredients": [{"name":"A dead animal","price":35},
                            {"name":"Its blood","price":5},
                            {"name":"some potatoes","price":10},
                            {"name":"asparagus","price":20},
                            {"name":"love","price":0}]},

        3: {"name": "dessert",
            "ingredients": [{"name":"Dough","price":9},
                            {"name":"Some Sprinkly shit","price":18},
                            {"name":"sugar","price":10},
                            {"name":"more sugar","price":10},
                            {"name":"cream shaboogy pop","price":13}]}
    };
    function getRecipeItems() {
        return recipeItems = [
            {
                "id": "recipe0",
                "title": "Grasshopper Cocktail",
                "img": "../images/recipeimages/grasshopper-cocktail.jpg",
                "ingredients": recipeType[0].ingredients,
                "instructions":"shaken not stirred",
                "price": 45, //shouldn't this be recipeType[0,1,2].sumprice somehow//
                "type" : recipeType[0].name,
            },
            {
                "id": "recipe1",
                "title": "Beef roast with veggies",
                "img": "../images/recipeimages/beef-roast-with-veggies.JPG",
                "ingredients": recipeType[2].ingredients,
                "instructions":"stuff it good",
                "price": 55,
                "type" : recipeType[2].name,
            },
            {
                "id": "recipe2",
                "title": "Shrimp-Fried-Rice",
                "img": "../images/recipeimages/Shrimp-Fried-Rice.jpg",
                "ingredients": recipeType[1].ingredients,
                "instructions":"extra MSG",
                "price": 65,
                "type" : recipeType[1].name,
            },
            {
                "id": "recipe3",
                "title": "Cupcake from hell",
                "img": "../images/recipeimages/Cupcake-Idea-pics-200x150.jpg",
                "ingredients": recipeType[3].ingredients,
                "instructions":"death is inevitable",
                "price": 15,
                "type" : recipeType[3].name,
            },
        ]
    }

    function createRecipeItem(recipeItem) {
        var recipeElement = document.createElement('div');
        recipeElement.setAttribute("id", recipeItem.id);
        recipeElement.setAttribute("class", recipeItem);

        recipeDetailsElement = document.createElement("div");
        recipeDetailsElement.setAttribute("id", recipeItem.id+"_details");

        recipeDetailsElement.appendChild(createDeleteRecipe(recipeItem));
        recipeDetailsElement.appendChild(createRecipePic(recipeItem));
        recipeDetailsElement.appendChild(createRecipeTitle(recipeItem));

        recipePreperationElement = document.createElement("div");
        recipePreperationElement.setAttribute("id", recipeItem.id+"_full_details");
        recipePreperationElement.appendChild(createRecipeIngredients(recipeItem));
        recipePreperationElement.appendChild(createRecipeInstructions(recipeItem));
        recipePreperationElement.style.display = 'none';

        recipeDetailsElement.appendChild(recipePreperationElement);


        recipeElement.appendChild(createUndoDeleteRecipe(recipeItem));
        recipeElement.appendChild(recipeDetailsElement);


        return recipeElement;

    }
    function createUndoDeleteRecipe(recipeItem) {
        var undoButton = document.createElement('span');
        undoButton.setAttribute("id", recipeItem.id + "_undo");
        undoButton.setAttribute("class", "fa fa-undo", "aria-hidden", "true");
        $(undoButton).hide();
        $(undoButton).click(() => {
            onItemDeleteUndo(recipeItem);
    });
        return undoButton;
    }
    function createDeleteRecipe(recipeItem) {
        var deleteButton = document.createElement('span');
        deleteButton.setAttribute("class", "fa fa-times-circle", "aria-hidden", "true");

        $(deleteButton).click(() => {
            onItemDelete(recipeItem);
    });

        return deleteButton;
    }

    function onItemDelete(recipeItem) {
        $('#'+recipeItem.id+'_details').hide();
        $('#'+recipeItem.id+'_undo').show();
    }

    function onItemDeleteUndo(recipeItem) {
        $('#'+recipeItem.id+'_details').show();
        $('#'+recipeItem.id+'_undo').hide();
    }

    function createRecipeTitle(recipeItem) {
        var div = document.createElement('div');
        div.innerHTML = recipeItem.title;
        return div;
    }

    function createRecipeInstructions(recipeItem) {
        var div = document.createElement('div');
        div.innerHTML = recipeItem.instructions;
        return div;
    }

    function createRecipePic(recipeItem) {
        var recipePic = document.createElement("img");
        recipePic.setAttribute("src", recipeItem.img);
        recipePic.setAttribute("class", "recipe");
        $(recipePic).css('margin-top', '10px');

        $(recipePic).click(() => {
            $('#'+recipeItem.id+"_full_details").slideToggle();
    });

        return recipePic;
    }

    function createRecipeIngredients(recipeItem) {
        var ingredients = document.createElement("ul");
        ingredients.setAttribute("id", recipeItem.id + "_ingredients");
        ingredients.className = "ingredientsList";

        recipeItem.ingredients.forEach(ingredient => {
            var li = document.createElement("li");
        li.className = "ingredients";
        li.setAttribute("type", "checkbox");

        var checkbox = document.createElement("input");
        checkbox.setAttribute("type", "checkbox");
        li.appendChild(checkbox);

        var ingredientElement = document.createElement("a");
        ingredientElement.innerHTML = ingredient;
        li.appendChild(ingredientElement);

        ingredients.appendChild(li);
    })
        return ingredients;

    }

    recipeItems = getRecipeItems();
    var mainContainer = document.getElementsByClassName('mainContainer');
    recipeItems.forEach(recipeItem => {
        mainContainer[0].appendChild(createRecipeItem(recipeItem));
});



};
var recipeItems;
var Merchantprices;
$(document).ready(main);

最佳答案

下面是错误的:

        {
            "id": "recipe0",
            "title": "Grasshopper Cocktail",
            "img": "../images/recipeimages/grasshopper-cocktail.jpg",
            "ingredients": recipeType[0].ingredients,
            "instructions":"shaken not stirred",
            "price": 45, //shouldn't this be recipeType[0,1,2].sumprice somehow//
            "type" : recipeType[0].name,
        }

这是一个由您的 getRecipeItems 函数返回的数组项。 当它们是字符串或数字时,您可以选择值并打印它们。 recipe[0].idrecipe[0].type

然而,当 recipe[0] 包含像 ingredients 这样的对象时,它会打印 [object Object]。要解决这个问题,您需要访问属性(或迭代它们)。

"ingredients": [{"name":"Booz","price":10}
                {"name":"Roofis","price":23},
                {"name":"Green Stuff","price":8}]}

recipe[0].ingredients.name 例如。

小型概念证明:

var main = function() {

  var recipeType = {
    0: {
      "name": "cocktail",
      "ingredients": [{
          "name": "Booz",
          "price": 10
        }, //shouldn't this be merchantPrices.Booz?//
        {
          "name": "Roofis",
          "price": 23
        },
        {
          "name": "Green Stuff",
          "price": 8
        }
      ]
    },

    1: {
      "name": "appetizer",
      "ingredients": [{
          "name": "Some leaves",
          "price": 7
        },
        {
          "name": "Some veggies",
          "price": 17
        },
        {
          "name": "I dunno toast",
          "price": 10
        },
        {
          "name": "Cheese or whatever",
          "price": 17
        }
      ]
    },

    2: {
      "name": "main course",
      "ingredients": [{
          "name": "A dead animal",
          "price": 35
        },
        {
          "name": "Its blood",
          "price": 5
        },
        {
          "name": "some potatoes",
          "price": 10
        },
        {
          "name": "asparagus",
          "price": 20
        },
        {
          "name": "love",
          "price": 0
        }
      ]
    },

    3: {
      "name": "dessert",
      "ingredients": [{
          "name": "Dough",
          "price": 9
        },
        {
          "name": "Some Sprinkly shit",
          "price": 18
        },
        {
          "name": "sugar",
          "price": 10
        },
        {
          "name": "more sugar",
          "price": 10
        },
        {
          "name": "cream shaboogy pop",
          "price": 13
        }
      ]
    }
  };

  function getRecipeItems() {
    return recipeItems = [{
        "id": "recipe0",
        "title": "Grasshopper Cocktail",
        "img": "../images/recipeimages/grasshopper-cocktail.jpg",
        "ingredients": recipeType[0].ingredients,
        "instructions": "shaken not stirred",
        "price": 45, //shouldn't this be recipeType[0,1,2].sumprice somehow//
        "type": recipeType[0].name,
      },
      {
        "id": "recipe1",
        "title": "Beef roast with veggies",
        "img": "../images/recipeimages/beef-roast-with-veggies.JPG",
        "ingredients": recipeType[2].ingredients,
        "instructions": "stuff it good",
        "price": 55,
        "type": recipeType[2].name,
      },
      {
        "id": "recipe2",
        "title": "Shrimp-Fried-Rice",
        "img": "../images/recipeimages/Shrimp-Fried-Rice.jpg",
        "ingredients": recipeType[1].ingredients,
        "instructions": "extra MSG",
        "price": 65,
        "type": recipeType[1].name,
      },
      {
        "id": "recipe3",
        "title": "Cupcake from hell",
        "img": "../images/recipeimages/Cupcake-Idea-pics-200x150.jpg",
        "ingredients": recipeType[3].ingredients,
        "instructions": "death is inevitable",
        "price": 15,
        "type": recipeType[3].name,
      },
    ]
  };

  //loop over each recipe:
  getRecipeItems().forEach(function(element) {
    //we use reduce to return all the ingredients in an array and join to glue together.
    var htmlSTRING = "<h2>"+element.title+"</h2>";    
    htmlSTRING += "<p>Ingredients: <br />" + element.ingredients.reduce(function(a,b){return a.concat(b.name)}, []).join("<br/>") + "</p>";
    htmlSTRING += "<p>Instructions: " + element.instructions + "</p>"; 
    
    document.querySelector("#recipes").insertAdjacentHTML("beforeend", htmlSTRING)
    
  });
};

main();
<div id="recipes"></div>

关于javascript - 如何从对象中检索数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47122754/

相关文章:

javascript - 如何在javascript中查找字符串的第一个字母是否为元音

javascript - JavaScript 中的数组 - 对数组中的文本和数字进行排序

javascript - 在 JavaScript 中使用数组存储一组具有设定值的变量

c# - 如何将 JSON 对象作为参数从 Postman 传递到 ASP.NET WEB API

java - Jackson:如何用键包装对象,这是序列化对象的属性之一?

javascript - 如何将 mouseenter() 或 mouseleave() 添加到同一类的多个元素?

javascript - AJAX Post 线上的数据格式

Python:在数组中填充多边形区域

javascript - Lodash:提取属性、分割数组、获取唯一值

javascript - 如何以 jQuery 方式搜索和操作复杂的 JavaScript 对象