首页 > 解决方案 > 您将如何将食谱存储在 json 中?

问题描述

您将如何将食谱存储在 json 中?我正在考虑存储一个食谱,我正在考虑这样做:

const recipes = {{
    id: 1,
    title: 'Omelette',
    recipe: 'Do something /n
    Do something else /n
    Do something else after that /n
    Do something else after that',
    ingredients: 'Ingredient1 /n
    Ingredient2 /n
    Ingredient3 /n',
    date: '',
}}

我正在考虑这样做,但我想知道是否有更好的方法。我应该像这样把线路跳过还是有更好的方法?

标签: javascriptjson

解决方案


在 JSON 中,你的食谱会像

const myObj = {recipes :[{"id":0,
                title: 'Omelette',
                 contents:["something","something"],
                 ingredients:["ing1","ing2"],
                 date: ''
                },
                {"id":1,
                 title: 'anything',
                 contents:["something","something"],
                 ingredients:["ing1","ing2"],
                 date: ''
                }
]};

这使您可以知道您有多少食谱或食谱的内容或成分

myObj.recipes.length

或者

myObj.recipes[0].contents.length

并且可以通过其索引访问任何食谱,您可以将 id 设置为其索引以轻松访问它

myObj.recipes[0].ingredients

通过这一行,您可以获得一系列成分,这些成分比使用字符串存储数据(如示例中的数据)更容易使用。所以如果你要修改一种成分,你只需要改变这个特定的成分,比如

myObj.recipes[0].ingredients[1]="new ing";

推荐阅读