-1

I have a function that grabs some values from JSON files, and creates an item object.

var searchIndex = [];

function getSearchTerms(param){

  var filePath = 'json/' + param + '.json';

  $.getJSON(filePath, function( data ) {

      var item = {
        param: param,
        title: data.title,
        person: data.fname + ' ' + data.lname
      };

      // console.log(item);
      // searchIndex.push(item);

      return item;
  });

}

I can see the item objects with correct properties being created when I check the console.

However, when I try to add the objects to searchIndex array, either within the function or within the loop that calls the getSearchTerms function, I get an array with the correct number of rows, but all the values are undefined.

var contentFiles = [ 'a', 'b', 'c'];

for (var i = 0; i < contentFiles.length; i++) {
    searchIndex.push( getSearchTerms(contentFiles[i]) );
}

What stupid thing am I doing wrong here? Thank you in advance for your help.

Rhecil Codes
  • 511
  • 4
  • 24

1 Answers1

0

Remember, reading files from the disk takes a little bit of time. Not a lot, but enough to mess with this little bit of code you're trying to write. Now's a good time for you to learn how to use asynchronous code. Here are some slight alterations to specific lines of code that might be able to help.

async function getSearchTerms(param)
await var item

within your loop...

await getSearchTerms(contentFiles[i])
searchIndex.push(object))

I'm no expert, and this is the first SO question I've ever answered. You might need a .next in there or something. If this doesn't work, look further into the concept of async/await functions. In your code, you're pushing objects that haven't gotten their actual value yet, because reading from disk takes a moment. JS travels line by line without waiting, and sometimes you'll have values that need a second to be sorted out.

JLang
  • 36
  • 1