javascript – 嵌套JSON:如何将新项目添加(推送)到对象?

我只是从Arrays,Objects和JSON开始 – 所以希望有一些简单的东西我在这里忽略。我试图添加(推)一个新的项目到我的json对象时遇到错误。

我遇到以下错误:表达式的结果’library.push'[undefined]不是一个函数(在我的代码片段的底部)。

请帮助!谢谢!

// This is my JSON object generated from a database
var library = {
    "Gold Rush" : {
        "foregrounds" : ["Slide 1","Slide 2","Slide 3"],
        "backgrounds" : ["1.jpg","","2.jpg"]
    }
    "California" : {
        "foregrounds" : ["Slide 1","Slide 2","Slide 3"],
        "backgrounds" : ["3.jpg","4.jpg","5.jpg"]
    }
}

// These will be dynamically generated vars from editor
var title = "Gold Rush";
var foregrounds = ["Howdy","Slide 2"];
var backgrounds = ["1.jpg",""];

function save () {

    // If title already exists, modify item
    if (library[title]) {
        // Replace values with new
        library[title].foregrounds = foregrounds;
        library[title].backgrounds = backgrounds;

        // Save to Database. Then on callback...
        document.write('Changes Saved to <b>'+title+'</b>');

    // If title does not exist, add new item
    else {
        // Format it for the JSON object
        var item = ('"'+title+'" : {"foregrounds" : '+foregrounds+',"backgrounds" : '+backgrounds+'}');


        // THE PROBLEM SEEMS TO BE HERE??
        // Error: "Result of expression 'library.push' [undefined] is not a function"
        library.push(item);


        // Save to Database. Then on callback...
        document.write('Added: <b>'+title+'</b>');
    }
}

save();
库是一个对象,而不是一个数组。你把东西推到数组上。与PHP不同,Javascript做出了区分。

您的代码尝试创建一个类似于键值对的源代码的字符串,然后将其“推”到对象上。这甚至不是接近它的工作原理。

您要做的是向对象添加一个新的键值对,其中键是标题,值是另一个对象。看起来像这样:

library[title] = {"foregrounds" : foregrounds, "backgrounds" : backgrounds};

“JSON对象”是一个模糊的术语。您必须小心区分程序中内存中的实际对象和JSON格式的文本片段。

翻译自:https://stackoverflow.com/questions/6503193/nested-json-how-to-add-push-new-items-to-an-object

转载注明原文:javascript – 嵌套JSON:如何将新项目添加(推送)到对象?