简体   繁体   English

将新元素添加到现有对象

[英]Add new element to an existing object

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 myFunction = {
    Author: 'my name ',
    date: '15-12-2012',
    doSomething: function(){
        alert("helloworld")
    }
};
myFunction.push({
    bookName:'mybook',
    bookdesc: 'new'
});
console.log(myFunction);

Use this: 用这个:

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

Or, if you are using jQuery: 或者,如果您使用jQuery:

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

The push method is wrong because it belongs to the Array.prototype object. push方法是错误的,因为它属于Array.prototype对象。

To create a named object, try this: 要创建命名对象,请尝试以下操作:

var myObj = function(){
    this.property = 'foo';
    this.bar = function(){
    }
}
myObj.prototype.objProp = true;
var newObj = new myObj();

Just do myFunction.foo = "bar" and it will add it. 只需执行myFunction.foo = "bar"添加它。 myFunction is the name of the object in this case. myFunction是这种情况下对象的名称。

jQuery syntax mentioned above by Danilo Valente is not working. Danilo Valente上面提到的jQuery语法不起作用。 It should be as following- 它应该如下 -

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

您可以使用Extend将新对象添加到现有对象。

You are looking for the jQuery extend method . 您正在寻找jQuery扩展方法 This will allow you to add other members to your already created JS object. 这将允许您将其他成员添加到已创建的JS对象中。

You could store your JSON inside of an array and then insert the JSON data into the array with push 您可以将JSON存储在数组中,然后使用push将JSON数据插入到数组中

Check this out https://jsfiddle.net/cx2rk40e/2/ 看看这个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) JSON.stringify(jsonTest)结果

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

This answer maybe useful to users who wish to emulate a similar result. 这个答案可能对希望模仿类似结果的用户有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM