0

Having some issues with finding an item in a JSON Array and passing it to a different array. The error I am getting appears to be that it's not properly passing the item out of the function. It is finding the item in the database, I can see it properly in console logs and view it properly with JSON.stringify.

Though, no matter how I have tried passing it out of the function (as a string, as an object etc.) it is not returning a value besides undefined.

If I do a console.log on newCard it will always come back as undefined.

Any help on this would be greatly appreciated, thank you.

var deckObject = [];
var newCard = findCard('EX1_123');
deckObject.push(newCard);

function findCard(cardId){
   $.each(cardDB, function(i, v) {
      if (v.id === cardId) {    
         v['count'] = 1;
         return v;
      }
    });

}

2 Answers 2

1

you should never return value from loop, rather use callback to manage asynchronous code

var deckObject = [];
var newCard = findCard('EX1_123',function(newcard){
  deckObject.push(newCard);
});

function findCard(cardId,callback){
   $.each(cardDB, function(i, v) {
      if (v.id === cardId) {    
         v['count'] = 1;
         callback(v);
      }
    });
}
Sign up to request clarification or add additional context in comments.

Comments

0

$.each doesn't return out of the function. Assign the returned value to a vraible and then return it.

function findCard(cardId){

   var res = $.each(cardDB, function(i, v) {

      if (v.id === cardId) { 
         console.log(v.id);
         v['count'] = 1;
         return v;
      }
    });
  return res;

}

Sample Snippet.

$(function(){
var cardDB = [
{
	id: '1',
  count: 0
},
{
	id: '2',
  count: 0
},
{
	id: '3',
  count: 0
}

]
var deckObject = [];
var newCard = findCard('1');
console.log(newCard);
deckObject.push(newCard);

function findCard(cardId){
   
   var opt = $.each(cardDB, function(i, v) {
     
      if (v.id === cardId) { 
         console.log(v.id);
         v['count'] = 1;
         return v;
      }
    });
  return opt;

}

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.