Add new element to an existing object

后端 未结 6 1804
走了就别回头了
走了就别回头了 2020-12-13 12:41

I was looking for a way to add new elements to an an existing object like what push does with arrays

I have tried this and it didn\'t work :

var myF         


        
相关标签:
6条回答
  • 2020-12-13 13:10

    Use this:

    myFunction.bookName = 'mybook';
    myFunction.bookdesc = 'new';
    

    Or, if you are using jQuery:

    $(myFunction).extend({
        bookName:'mybook',
        bookdesc: 'new'
    });
    

    The push method is wrong because it belongs to the Array.prototype object.

    To create a named object, try this:

    var myObj = function(){
        this.property = 'foo';
        this.bar = function(){
        }
    }
    myObj.prototype.objProp = true;
    var newObj = new myObj();
    
    0 讨论(0)
  • 2020-12-13 13:15

    You are looking for the jQuery extend method. This will allow you to add other members to your already created JS object.

    0 讨论(0)
  • 2020-12-13 13:16

    Just do myFunction.foo = "bar" and it will add it. myFunction is the name of the object in this case.

    0 讨论(0)
  • 2020-12-13 13:21

    You could store your JSON inside of an array and then insert the JSON data into the array with push

    Check this out https://jsfiddle.net/cx2rk40e/2/

    $(document).ready(function(){
    
      // using jQuery just to load function but will work without library.
      $( "button" ).on( "click", go );
    
      // Array of JSON we will append too.
      var jsonTest = [{
        "colour": "blue",
        "link": "http1"
      }]
    
      // Appends JSON to array with push. Then displays the data in alert.
      function go() {    
          jsonTest.push({"colour":"red", "link":"http2"});
          alert(JSON.stringify(jsonTest));    
        }
    
    }); 
    

    Result of JSON.stringify(jsonTest)

    [{"colour":"blue","link":"http1"},{"colour":"red","link":"http2"}]
    

    This answer maybe useful to users who wish to emulate a similar result.

    0 讨论(0)
  • 2020-12-13 13:26

    You can use Extend to add new objects to an existing one.

    0 讨论(0)
  • 2020-12-13 13:28

    jQuery syntax mentioned above by Danilo Valente is not working. It should be as following-

    $.extend(myFunction,{
        bookName:'mybook',
        bookdesc: 'new'
    });
    
    0 讨论(0)
提交回复
热议问题