Javascript array with for loop, returns only last element

前端 未结 2 1801
梦如初夏
梦如初夏 2021-01-01 05:39

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

2条回答
  •  感情败类
    2021-01-01 06:27

    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
        };
    })
    

提交回复
热议问题