Pushing objects in an array only returns last object pushed

北城以北 提交于 2021-01-24 14:39:48

问题


I am working on YUI DataTables, to populate the data table i want to send the columns and their values dynamically from outside, for that i have written the following code:

<html>
<script src="http://yui.yahooapis.com/3.17.2/build/yui/yui-min.js"></script>
<div class="example yui3-skin-sam" id="simple"> <!-- You need this skin class -->
</div>

<script>
var cols = ["id", "name", "price"];
var obj = {
    id: "",
    name: "",
    price: ""
};
var data2 = new Array();
obj.id = "ga";
obj.name = "gadget";
obj.price = "$6.99";
data2.push(obj);
obj.id = "ga2";
obj.name = "gadget2";
obj.price = "$7.99";
data2.push(obj);
obj.id = "ga3";
obj.name = "gadget3";
obj.price = "$8.99";
data2.push(obj);
YUI().use("datatable", function (Y) {
    // A table from data with keys that work fine as column names
    var simple = new Y.DataTable({
        columns: cols,
        data   : data2,
        summary: "Price sheet for inventory parts",
        caption: "Example table with simple columns"
    });

    simple.render("#simple");

});
</script>
</html>

now the problem is that, it shows only the last obj pushed in data2.. kindly tell me why its not displaying all three objs. the resulting table from this code is

id      name    price

ga3   gadget3   $8.99

回答1:


it will give all array values

function obj(id, name, price) {
     this.id = id;
     this.name = name;
     this.price = price;
 }

 var array = new Array();

 var point = new obj("ga", "gadget", "$6.99");

 array.push(point);

 var point = new obj("ga2", "gadget2", "$7.9");

 array.push(point);



回答2:


Not sure if this is relevant anymore but if people still come here looking for an easy solution...

Just stringify the object and JSON.parse it again to copy it instead of referencing the object like so;

data2.push(JSON.parse(JSON.stringify(obj)));



回答3:


Both answers above (2480125, 2480125) will work, but they require that you manually input the new object's properties for every new object added to the array.

You can avoid that inflexibility with a for..in loop (docs):

var newObj = function(object) {
  var newObject = {};
  for (var key in object) {
    if (object.hasOwnProperty(key)) {
      newObject[key] = object[key];
    }
  }
  return newObject;
};

var obj = {
  id: 'foo',
  name: 'gadget',
  price: '$6.99'
};

data2 = [];

data2.push( newObj(obj) );

obj.id = 'bar';
obj.name = 'baz';
obj.price = '$4.44';

data2.push( newObj(obj) );

console.log(data2);
data2.forEach(function(item){
  console.log("%s, %s, %s", item.id, item.name, item.price);
});
// data2 now contains two distinct objects, rather than one object reference added to the array twice.

JSFiddle for above code




回答4:


Objects are reference objects.

obj.id = "ga";
obj.name = "gadget";
obj.price = "$6.99";
data2.push(obj);

obj.id = "ga2";
obj.name = "gadget2";
obj.price = "$7.99";
data2.push(obj);

This means that when you update the obj the second time, you're actually updating all references to that object.

If you examine your data2 array you'll see that it has 3 elements and that all elements are the same.

try updating your code to something like this

data2.push({
    id : "ga",
    name : "gadget",
    price : "$6.99"
});
data2.push{(
    id : "ga2",
    name : "gadget2",
    price : "$7.99"
)};
data2.push({
    id : "ga3",
    name : "gadget3",
    price : "$8.99"
});



回答5:


None of these answers worked for me, and I can't explain why it worked, but adding a character value to the element I was pushing inline was the only way I could get it to work properly. I tried the suggestions of creating new objects or even just creating new variables and pushing either the new object or new variables but to no avail, it just kept rewriting each element of the array whenever it would push a new element such that the entire array would be the final value of the loop each time. So in the end this is what I had to do to get it to work:

var returnArray = [];
while(...){
    returnArray.push('' + obj.value);
}


来源:https://stackoverflow.com/questions/25321777/pushing-objects-in-an-array-only-returns-last-object-pushed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!