Home > Software engineering >  array has got same item every push
array has got same item every push

Time:05-16

Array Push will replace old value, with new one, bot i dont understand why this happend.

this is my code:

    let meta = [];

    let counter = 0;
    let temp_item = {}

    for (let ele of found_spec) {

        let ele_clean = cleanItem(ele)
        if (ele.includes(':<')) {
            temp_item.label = ele_clean;
        } else {
            temp_item.value = ele_clean;
        }
        counter  ;

        if ((counter % 2) == 0) {
            meta.push(temp_item)
        }
    }

    let oggetto = {
        "id_kromeda": id_kromeda,
        "picture": found_picture[1],
        "description": found_descrizione[1],
        "meta": meta //<--- here is my array with overwritten old values
    }
    console.log(oggetto); //<---  breakpoint here
}

Here is the screenshot of oggetto console.log(oggetto), that include, my array called meta

enter image description here

CodePudding user response:

You have one object temp_item that you create before your loop. Then, your loop just sets properties on that one object and then pushes the object into the array. Since pushing into an array does NOT create a copy of the object, you end up just modifying the same object over and over in the loop and pushing the same object over and over into the array.

So, you get an array of all the same object that have the properties as set by the last iteration of your loop.

You can fix it by creating a new temp_item object after you push the previous one into the array, thus you end up with a new object in the array each time you do meta.push(temp_item).

let meta = [];

let counter = 0;
let temp_item = {};

for (let ele of found_spec) {

    let ele_clean = cleanItem(ele)
    if (ele.includes(':<')) {
        temp_item.label = ele_clean;
    } else {
        temp_item.value = ele_clean;
    }
    counter  ;

    if ((counter % 2) == 0) {
        meta.push(temp_item);
        // now create a new temp_item object for future iterations
        temp_item = {};
    }
}
  • Related