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

后端 未结 4 1418
礼貌的吻别
礼貌的吻别 2020-12-02 15:53

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

4条回答
  •  暖寄归人
    2020-12-02 16:16

    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.

提交回复
热议问题