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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6503193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:04:39  来源:igfitidea点击:

Nested JSON: How to add (push) new items to an object?

javascriptjqueryjson

提问by Josiah

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.

我只是从数组、对象和 JSON 开始 - 所以希望我在这里忽略了一些简单的东西。尝试新项目添加(推送)到我的 json 对象时遇到错误。

I'm encountering the following error: Result of expression 'library.push' [undefined] is not a function(towards the bottom of my code snippet).

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

回答by Karl Knechtel

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

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

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 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 对象”是一个模糊的术语。您必须小心区分程序内存中的实际对象和 JSON 格式的文本片段。

回答by Rodrigo Durán Roubillard

If your JSON is without key you can do it like this:

如果您的 JSON 没有密钥,您可以这样做:

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

So, try this:

所以,试试这个:

var library = {[{
    "title"       : "Gold Rush",
        "foregrounds" : ["Slide 1","Slide 2","Slide 3"],
        "backgrounds" : ["1.jpg","","2.jpg"]
    }, {
    "title"       : California",
        "foregrounds" : ["Slide 1","Slide 2","Slide 3"],
        "backgrounds" : ["3.jpg","4.jpg","5.jpg"]
    }]
}

Then:

然后:

library[library.length] = {"title" : "Gold Rush", "foregrounds" : ["Howdy","Slide 2"], "backgrounds" : ["1.jpg",""]};

回答by jerjer

push is an Array method, for json object you may need to define it

push 是一个 Array 方法,对于 json 对象,您可能需要定义它

this should do it:

这应该这样做:

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

回答by Penny Liu

You can achieve this using Lodash_.assignfunction.

您可以使用Lodash_.assign函数来实现这一点

library[title] = _.assign({}, {'foregrounds': foregrounds }, {'backgrounds': backgrounds });

// 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]) {

    // override one Object with the values of another (lodash)
    library[title] = _.assign({}, {
      'foregrounds': foregrounds
    }, {
      'backgrounds': backgrounds
    });
    console.log(library[title]);

    // Save to Database. Then on callback...
    // console.log('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...
    console.log('Added: <b>' + title + '</b>');
  }
}

save();
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>