简体   繁体   English

遍历对象文字的属性

[英]Iterate through properties of a object literal

I have the following code to save some values to the local storage and display it afterwards as a list. 我有以下代码将一些值保存到本地存储中,然后将其显示为列表。 The problem I have is with displayRecipes(). 我的问题是displayRecipes()。 It only displays the recipeName value and everything else is undefined. 它仅显示配方名称值,其他所有内容均未定义。 As you can see I store all recipes in localStorage.recipes with the recipe name on the top level and all the other values as "sub-properties" like this: {'recipeName: {'other values and properties'...}}. 如您所见,我将所有配方存储在localStorage.recipes中,配方名称位于顶层,所有其他值都作为“子属性”存储,如下所示:{'recipeName:{'other values and properties'...}} 。 I'm fairly new to JavaScript so I just thought 'undefined' means that the variables have not been initialized correctly. 我对JavaScript相当陌生,所以我只是认为“未定义”意味着变量未正确初始化。 I'm initializing and assigning them in addNewRecipe() but by the time I want to display them they're already stored in local storage. 我正在addNewRecipe()中初始化并分配它们,但是到我想要显示它们时,它们已经存储在本地存储中。

Thank you in advance for any help. 预先感谢您的任何帮助。

function addNewRecipe() {
    var recipeName = $('#recipeName').val();
    var recipeType = $('#recipeType').val();
    var recipePersonsCount = $('#recipePersonsCount').val();
    var recipeTime = $('#recipeTime').val();
    var recipeContents = $('#recipeContents').val();
    var recipeInstructions = $('#recipeInstructions').val();

    // Checks if recipes variable already exists
    // If yes: get content, parse it, add new data to array and store it again
    // If no: create new variable and store it
    if (localStorage.recipes) {
        var getRecipes = JSON.parse(localStorage.getItem('recipes'));
        var newRecipe = getRecipes;
        newRecipe[recipeName] = {'recipeType': recipeType, 'recipePersonsCount': recipePersonsCount,
                                 'recipeTime': recipeTime, 'recipeContents': recipeContents,
                                 'recipeInstructions': recipeInstructions};
        localStorage.setItem('recipes', JSON.stringify(newRecipe));
    } else {
        var recipe = {};
        recipe[recipeName] = {'recipeType': recipeType, 'recipePersonsCount': recipePersonsCount,
                                'recipeTime': recipeTime, 'recipeContents': recipeContents,
                                'recipeInstructions': recipeInstructions};
        localStorage.setItem('recipes', JSON.stringify(recipe));
    };
};

function getRecipes() {
    var existingRecipes = JSON.parse(localStorage.getItem('recipes'));
    return existingRecipes;
};

function displayRecipes() {
    var recipes = getRecipes();
    for (var key in recipes) {
        if (!$('#rec').val()) {
            $('#recipeList').add('<ul id="#rec">' + key + '</ul>').appendTo(document.body);
            $('#rec').add('<li>' + key.recipeType + '</li>').appendTo(document.body);
            $('#rec').add('<li>' + key.recipePersonsCount + '</li>').appendTo(document.body);
            $('#rec').add('<li>' + key.recipeTime + '</li>').appendTo(document.body);
            $('#rec').add('<li>' + key.recipeContents + '</li>').appendTo(document.body);
            $('#rec').add('<li>' + key.recipeInstructions + '</li>').appendTo(document.body);
        }
    }
};

You are accessing your object values wrong. 您访问的object值错误。

Change 更改

function displayRecipes() {
    var recipes = getRecipes();
    for (var key in recipes) {
        if (!$('#rec').val()) {
            $('#recipeList').add('<ul id="#rec">' + key + '</ul>').appendTo(document.body);
            $('#rec').add('<li>' + key.recipeType + '</li>').appendTo(document.body);
            $('#rec').add('<li>' + key.recipePersonsCount + '</li>').appendTo(document.body);
            $('#rec').add('<li>' + key.recipeTime + '</li>').appendTo(document.body);
            $('#rec').add('<li>' + key.recipeContents + '</li>').appendTo(document.body);
            $('#rec').add('<li>' + key.recipeInstructions + '</li>').appendTo(document.body);
        }
    }
};

to

function displayRecipes() {
    var recipes = getRecipes();
    for (var key in recipes) {
        if (!$('#rec').val()) {
            $('#recipeList').add('<ul id="#rec">' + recipes[key] + '</ul>').appendTo(document.body);
            $('#rec').add('<li>' + recipes[key].recipeType + '</li>').appendTo(document.body);
            $('#rec').add('<li>' + recipes[key].recipePersonsCount + '</li>').appendTo(document.body);
            $('#rec').add('<li>' + recipes[key].recipeTime + '</li>').appendTo(document.body);
            $('#rec').add('<li>' + recipes[key].recipeContents + '</li>').appendTo(document.body);
            $('#rec').add('<li>' + recipes[key].recipeInstructions + '</li>').appendTo(document.body);
        }
    }
};

When iterating over objects, either make sure to use hasOwnProperty to filter: 遍历对象时,请确保使用hasOwnProperty进行过滤:

var o = { ... };
for (var p in o) {
  if (o.hasOwnProperty(p)) {
    // process o[p]
  }
}

or use the Object.keys() that filters for you: 或使用为您过滤的Object.keys()

for (var p in Object.keys(o)) {
  // process o[p]
}

I just noticed in your code: 我刚刚在您的代码中注意到:

newRecipe[recipeName] = {
    'recipeType': recipeType, 'recipePersonsCount': recipePersonsCount,
    'recipeTime': recipeTime, 'recipeContents': recipeContents,
    'recipeInstructions': recipeInstructions
};

You don't need to use apostrophes unless the key contains characters such as - or numbers. 除非键包含-或数字之类的字符, 否则无需使用撇号。

This is valid: 这是有效的:

var object = {
    firstname: 'Bob'
}

This is invalid: 这是无效的:

var object = {
    first-name: 'Bob'
}

But, this is valid: 但是,这是有效的:

var object = {
    'first-name': 'Bob'
}

This is invalid: 这是无效的:

var object = {
    0: 'Bob'
}

But, this is valid: 但是,这是有效的:

var object = {
    '0': 'Bob'
}

Your code will still work if you change it to this: 如果将其更改为此,您的代码仍将起作用:

newRecipe[recipeName] = {
    recipeType: recipeType, recipePersonsCount: recipePersonsCount,
    recipeTime: recipeTime, recipeContents: recipeContents,
    recipeInstructions: recipeInstructions
};

You can write it like that, but normally, we might list them because it's more clear: 您可以这样写,但通常情况下,我们可能会列出它们,因为它更清楚:

newRecipe[recipeName] = {
    recipeType: recipeType,
    recipePersonsCount: recipePersonsCount,
    recipeTime: recipeTime,
    recipeContents: recipeContents,
    recipeInstructions: recipeInstructions
};

Now, here's where it gets sweet. 现在,这里变得甜美了。 You can use ES6 Object Literal Shorthand Syntax . 您可以使用ES6 Object Literal Shorthand Syntax If an object's property key is the same as the variable name assigned to its value, you can do this: 如果对象的属性键与为其值分配的变量名称相同,则可以执行以下操作:

newRecipe[recipeName] = {
    recipeType,
    recipePersonsCount,
    recipeTime,
    recipeContents,
    recipeInstructions
};

Try it out in your code :) 在您的代码中尝试一下:)

To visualize it a bit better, run this sampler pack: 为了更好地显示它,请运行以下采样器包:

 var test = '100% neat'; var bonus = true; var cool = { test, bonus }; console.log(cool); console.log('Confirmed:', cool.test); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM