Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

212
Vistas
Javascript array value is undefined inside loop

I am trying to compare two objects. If an item inside checkedList is also found inside savedList I would like to copy the first item in the array from checkedList and place it with the found item in savedList. If items inside the checkedList is not found in the savedList I want to add the entire item to savedList. I dont wish to keep the same item twice inside the savedList. I am using the pop/push method to do this.

Problem I am running into is inside the [ while->for loop].

Uncaught TypeError: Cannot read properties of undefined (reading '1') When an item is found inside the savedList I wish to make the necessary alteration then move to the next item via pop(). However, when I use the pop() method the previous item is lost. Below is my working code as well as a link to JSFiddle.

Desired Output :

savedItemList = {
    "listName": "List_daily:Daily Get From Back List",
    "date": "",
    "itemList": [
      [  11, 888 ], [  55, 227 ],  [  44, 236 ],
      [  3, 700 ],  [  2, 600 ]
    ]
};

var savedItemList = {
    "listName": "List_daily:Daily Get From Back List",
    "date": "",
    //itemList contains [item quantity, item ID]
    "itemList": [
      [  1, 888 ], [  2, 227 ],  [  3, 236 ],
      [  3, 700 ],  [  2, 600 ]
    ]
};

var checkedItemList = [
    //itemData contains [item quantity, item ID]
    { "rowNumber": 1,  "itemData": [ 11, 888 ]  },
    { "rowNumber": 4,  "itemData": [ 44, 236 ]  },
    { "rowNumber": 3,  "itemData": [ 55,  227]  }
];

function moveItemsToList(savedItemList, checkedItemList)
{
  //while checkedItemList length is not zero
     while(checkedItemList.length)
     {
     //pop the last element inside checkedList
         var temp = checkedItemList.pop().itemData;
     //loop through the items inside savedList
     for(let k=0; k < savedItemList.itemList.length; k++)
        {
      //compare temp[1] itemID with savedList itemID
            if(temp[1] == savedItemList.itemList[k][1])
            {
        //if found save the quantity from temp[0] variable to savedItemList 
                savedItemList.itemList[k][0] = temp[0];
        //then move onto the next item on checkedList
                temp = checkedItemList.pop();
            }
        }
     //if items from CheckedList not Found in savedList        //Add the item and its quantity to savedList
        savedItemList.itemList.push(temp);
            
     }
     console.log(savedItemList);    
     
}

moveItemsToList(savedItemList, checkedItemList);

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Use modern JavaScript Array methods.

const savedItemList = {
    "listName": "List_daily:Daily Get From Back List",
    "date": "",
    //itemList contains [item quantity, item ID]
    "itemList": [
      [  1, 888 ], [  2, 227 ],  [  3, 236 ],
      [  3, 700 ],  [  2, 600 ]
    ]
};

const checkedItemList = [
    //itemData contains [item quantity, item ID]
    { "rowNumber": 1,  "itemData": [ 11, 888 ]  },
    { "rowNumber": 4,  "itemData": [ 44, 236 ]  },
    { "rowNumber": 3,  "itemData": [ 55,  227]  }
];

function moveCheckedToSaved(savedItemList, checkedItemList) {
  checkedItemList.forEach((checkedItem) => {
    const itemID = checkedItem.itemData[1]
    const dupeIndex = findDuplicate(itemID, savedItemList)
    if (dupeIndex !== -1) {
      savedItemList[dupeIndex][0] = checkedItem.itemData[0]
    } else {
      savedItemList.push(checkedItem.itemData)
    }
  })
}

function findDuplicate(id, list) {
  return list.findIndex(item => item[1] === id)
}

moveCheckedToSaved(savedItemList.itemList, checkedItemList)
document.write(savedItemList.itemList.join(' '))

about 4 years ago · Juan Pablo Isaza Denunciar

0

I assume you want to keep the data inside checkedItemList since you said copy. The code below solves your problem however I have rewritten the whole function.

var savedItemList = {
    "listName": "List_daily:Daily Get From Back List",
    "date": "",
    //itemList contains [item quantity, item ID]
    "itemList": [
      [  1, 888 ], [  2, 227 ],  [  3, 236 ],
      [  3, 700 ],  [  2, 600 ]
    ]
};

var checkedItemList = [
    //itemData contains [item quantity, item ID]
    { "rowNumber": 1,  "itemData": [ 11, 888 ]  },
    { "rowNumber": 4,  "itemData": [ 44, 236 ]  },
    { "rowNumber": 3,  "itemData": [ 55,  227]  }
];

function moveItemsToList(savedItemList, checkedItemList){
  
  //loop through checkItemList with checkedItem as the currently looped object
  for(let checkedItem of checkedItemList){
    itemData = checkedItem.itemData; //itemData is "itemData": [ quantity, ID ]"

    //loop through savedItemList.itemList with savedItem as the currently looped array
    for(let savedItem of savedItemList.itemList){

      //check if the IDs between checkedItemList.itemData and savedItemList.itemList matched
      if(itemData[1] === savedItem[1]){

        //delete the matched data from savedItemList.itemList and break the savedItemList.itemList loop
        savedItemList.itemList.splice(savedItemList.itemList.indexOf(savedItem), 1);
        break;
      }
    }

    //add new data to savedItemList.itemList
    itemDataToBeAdded = itemData;
    savedItemList.itemList.push(itemDataToBeAdded);
  }
  console.log(savedItemList);
}

moveItemsToList(savedItemList, checkedItemList);

EDIT: replaced for in loop with for of loop because for in is deprecated

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda