嵌套JSON:如何将新项添加(推送)到对象? [英] Nested JSON: How to add (push) new items to an object?

查看:126
本文介绍了嵌套JSON:如何将新项添加(推送)到对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用Arrays,Objects和JSON - 所以希望我能在这里看到一些简单的东西。我在尝试添加(推送)一个新项目到我的json对象时遇到错误。

I'm just starting with Arrays, Objects, and JSON - so hopefully there's just something simple I'm overlooking here. I'm encountering an error when attempting to add (push) a new item into my json object.

我遇到以下错误:表达式'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();


推荐答案

library 是一个对象,而不是一个数组。你把东西推到了数组上。与PHP不同,Javascript有所区别。

library is an object, not an array. You push things onto arrays. Unlike PHP, Javascript makes a distinction.

您的代码尝试创建一个类似于键值对的源代码的字符串,然后将其推送到物体。这甚至都不及它的工作原理。

Your code tries to make a string that looks like the source code for a key-value pair, and then "push" it onto the object. That's not even close to how it works.

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

What you want to do is add a new key-value pair to the object, where the key is the title and the value is another object. That looks like this:

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

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

"JSON object" is a vague term. You must be careful to distinguish between an actual object in memory in your program, and a fragment of text that is in JSON format.

这篇关于嵌套JSON:如何将新项添加(推送)到对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆