迭代对象文字

时间:2017-10-01 10:15:35

标签: javascript object

我有以下代码将一些值保存到本地存储,然后将其显示为列表。我遇到的问题是displayRecipes()。它只显示recipeName值,其他所有内容都是未定义的。如您所见,我将所有食谱存储在localStorage.recipes中,食谱名称位于顶层,所有其他值存储为“子属性”,如下所示:{'recipeName:{'其他值和属性'...}} 。 我对JavaScript很新,所以我只是认为'undefined'意味着变量尚未正确初始化。我正在初始化并在addNewRecipe()中分配它们,但是当我想要显示它们时,它们已经存储在本地存储中。

提前感谢您的帮助。

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

3 个答案:

答案 0 :(得分:0)

您错误地访问了object值。

更改

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

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

答案 1 :(得分:0)

在迭代对象时,要么确保使用hasOwnProperty来过滤:

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

或使用为您过滤的Object.keys()

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

答案 2 :(得分:0)

我刚才在你的代码中注意到了:

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

您不需要使用撇号,除非该键包含-或数字等字符。

这是有效的:

var object = {
    firstname: 'Bob'
}

这是无效的:

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

但是,这是有效的:

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

这是无效的:

var object = {
    0: 'Bob'
}

但是,这是有效的:

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

如果您将其更改为此代码,您的代码仍然有效:

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

你可以这样写,但通常我们可能会列出它们,因为它更清楚:

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

现在,这里变得甜美。您可以使用ES6 Object Literal Shorthand Syntax。如果对象的属性键与分配给其值的变量名相同,则可以执行以下操作:

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

在您的代码中尝试:)

为了更好地可视化,请运行此采样器包:

var test = '100% neat';
var bonus = true;

var cool = {
    test,
    bonus
};

console.log(cool);
console.log('Confirmed:', cool.test);