简体   繁体   中英

How to resolve javascript objects pushed in to individual arrays instead of all of them being pushed into a single array?

I have a javascript code as below:

function ready() {

    var items = document.querySelectorAll('.item')

    for (var i = 0; i < items.length; i++) {
        var current = items[i];

        var name = current.getElementsByClassName('item-title')[0].innerText;
        var price = parseInt(current.getElementsByClassName('item-price')[0].innerText);

        var data = [];

        var products = {};
        products.title = name;
        products.cost = price;
        data.push(products);

        //console.log(products)

        console.log(data)

    }
    
}

On running the code, I get the result as:

[{title: "Jack Daniels 1L", cost: 60}]
[{title: "Southern Comfort 2L", cost: 130}] 
[{title: "Golden Label 1L", cost: 120}]
[{title: "Grey Goose 1L", cost: 31}]
[{title: "Remy Martins 750ml", cost: 45}]
[{title: "Hennessy 1L", cost: 68}]
[{title: "Johnnie Walker 1L", cost: 50] 
[{title: "Double Black 750ml", cost: 55}]

Yet I'm looking for a result that looks like this:

[ {title: "Jack Daniels 1L", cost: 60}, 
   {title: "Southern Comfort 2L", cost: 130}, 
   {title: "Golden Label 1L", cost: 120}, 
   {title: "Grey Goose 1L", cost: 31}, 
   {title: "Remy Martins 750ml", cost: 45}, 
   {title: "Hennessy 1L", cost: 68}, 
   {title: "Johnnie Walker 1L", cost: 50}, 
   {title: "Double Black 750ml", cost: 55} ]

I have looked at solutions to questions asked that are related to mine but I keep getting the same result at best. What do I need to include or remove? Or what is the best way to go about it? Thank you.

So this is due to data being defined in each iteration. Move it out and it will work

function ready() {

    var items = document.querySelectorAll('.item')

    var data = [];

    for (var i = 0; i < items.length; i++) {
        var current = items[i];

        var name = current.getElementsByClassName('item-title')[0].innerText;
        var price = parseInt(current.getElementsByClassName('item-price')[0].innerText);

        var products = {};
        products.title = name;
        products.cost = price;
        data.push(products);

        //console.log(products)

    }

   console.log(data)
    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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