最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript array with for loop, returns only last element - Stack Overflow

programmeradmin3浏览0评论

I have a for loop, that adds data into an array. but when I console.log the array, it is full of the last item of the for loop!

Here is my code :

var materialsData = results[1].data, // results[1].data is a http.get return
ln = Object.size(materialsData),
materials = [],
material = {};
material['Product'] = {};

for (var i = 0; i < ln; i++) {
    material.Product['Name'] = materialsData[i].Product.Name;
    material.Product['Id'] = materialsData[i].Product.Id;
    material.StartingDate = materialsData[i].StartingDate.replace("T00:00:00", "").split('-').reverse().join('-');
    material.Device = materialsData[i].Device;
    materials.push(material);
}

I have a for loop, that adds data into an array. but when I console.log the array, it is full of the last item of the for loop!

Here is my code :

var materialsData = results[1].data, // results[1].data is a http.get return
ln = Object.size(materialsData),
materials = [],
material = {};
material['Product'] = {};

for (var i = 0; i < ln; i++) {
    material.Product['Name'] = materialsData[i].Product.Name;
    material.Product['Id'] = materialsData[i].Product.Id;
    material.StartingDate = materialsData[i].StartingDate.replace("T00:00:00", "").split('-').reverse().join('-');
    material.Device = materialsData[i].Device;
    materials.push(material);
}
Share Improve this question edited Jan 16, 2017 at 11:51 Satpal 133k13 gold badges167 silver badges170 bronze badges asked Jan 16, 2017 at 11:39 vierolivieroli 3761 gold badge5 silver badges17 bronze badges 2
  • 2 Where and how have you defined variable material? – Satpal Commented Jan 16, 2017 at 11:40
  • Objects are passed by reference. So every iteration, you are overriding same variable – Rajesh Commented Jan 16, 2017 at 11:40
Add a ment  | 

3 Answers 3

Reset to default 5

Define material in the for block. As Objects are passed by reference same object is updated and pushed to the array.

for (var i = 0; i < ln; i++) {
    var material = {
        Product : {
            Name : materialsData[i].Product.Name,
            Id : materialsData[i].Product.Id,
        },
        StartingDate : materialsData[i].StartingDate.replace("T00:00:00", "").split('-').reverse().join('-'),
        Device : materialsData[i].Device
    };
    materials.push(material);
}

Additionally, You can use Array.map()

var materials = materialsData.map(function(m){
    return {
        Product : {
            Name : m.Product.Name,
            Id : m.Product.Id,
        },
        StartingDate : m.StartingDate.replace("T00:00:00", "").split('-').reverse().join('-'),
        Device : m.Device
    };
})

You are updating and pushing the same object reference again and again so the object holds the last element values. Instead, initialize the object holding variable inside the for loop beginning.

for(var i=0; i<ln; i++){
  // initialize the object
  var material = { Product : {}, Id : {}};

  material.Product['Name'] = materialsData[i].Product.Name;
  material.Product['Id'] = materialsData[i].Product.Id;
  material.StartingDate = materialsData[i].StartingDate.replace("T00:00:00", "").split('-').reverse().join('-');
  material.Device = materialsData[i].Device;
  materials.push(material);
}

Or directly define the object as the argument of push method without holding it to any variable.

for (var i = 0; i < ln; i++) {
  materials.push({
    Product: {
      Name: materialsData[i].Product.Name,
      Id: materialsData[i].Product.Id,
    },
    StartingDate: materialsData[i].StartingDate.replace("T00:00:00", "").split('-').reverse().join('-'),
    Device: materialsData[i].Device
  })
}

You are indeed referencing the same object. For me the trick was to wrap the object in question around JSON.stringify() and then within the loop I call JSON.parse() on the resulting string to turn it back

var materialsDataString = JSON.stringify(results[1].data), // results[1].data is a http.get return
ln = Object.size(materialsData),
materials = [],
material = {};
material['Product'] = {};

for (var i = 0; i < ln; i++) {
    var materialsData = JSON.parse(materialsDataString)
    material.Product['Name'] = materialsData[i].Product.Name;
    material.Product['Id'] = materialsData[i].Product.Id;
    material.StartingDate = materialsData[i].StartingDate.replace("T00:00:00", "").split('-').reverse().join('-');
    material.Device = materialsData[i].Device;
    materials.push(material);
}

.

发布评论

评论列表(0)

  1. 暂无评论