开发者

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

开发者 https://www.devze.com 2023-03-16 01:11 出处:网络
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

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.

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

// 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","S开发者_Python百科lide 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 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 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.


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

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",""]};


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

this should do it:

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


You can achieve this using Lodash _.assign function.

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/lodash@4.17.10/lodash.min.js"></script>

0

精彩评论

暂无评论...
验证码 换一张
取 消