Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

214
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda