小编典典

嵌套JSON:如何向对象添加(推送)新项目?

json

我只是从数组,对象和JSON开始-希望这里有一些简单的事情我可以忽略。尝试 新项目 添加(推入) 我的json对象时遇到错误。

我遇到以下错误:(Result of expression 'library.push' [undefined] is not a function
接近我的代码段的底部)

// 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();

阅读 266

收藏
2020-07-27

共1个答案

小编典典

library是一个对象,而不是数组。您将事物推入阵列。与PHP不同,Javascript具有区别。

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

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

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

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

2020-07-27