blahdot3h
blahdot3h

Reputation: 1

Finding Item in JSON Array and adding it to another Array. Javascript

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;
      }
    });

}

Upvotes: 0

Views: 44

Answers (2)

Shubham Khatri
Shubham Khatri

Reputation: 281854

$.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>

Upvotes: 0

A.T.
A.T.

Reputation: 26332

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);
      }
    });
}

Upvotes: 1

Related Questions