1

I've searched the forums for this but I'm not sure where to start with this.

I was wondering if it's possible to create a reusable $.getJSON or $.each() function to create product html. To clarify, I'm creating a site which has multiple getjson functions actually doing the same work over and over again.

So function a() does a json request and with that data it creates some product html. Function b() does a json request to a different location but creates the same product html.

I'm just trying to write with less code :)

To give an example:

function abc() {
  $.getJSON(url-to-a, function(data) {
    var products = [];
      $.each(data.bundle.products, function(index, product) {
        var productHtml = '<div class="item">'+ product.title + '</div>'
        products.push(productHtml);
      });
      products.join('');
      container.html(products);
   });
 }

function xyz() {
  $.getJSON(url-to-different-location, function(data) {
    var products = [];
      $.each(data.search.products, function(index, product) {
        var productHtml = '<div class="item">'+ product.title + '</div>'
        products.push(productHtml);
      });
      products.join('');
      container.html(products);
   });
 }

As you can see it are different functions but mostly doing the same work. Especially in the $.each() function.

What I was wondering if it's possible to create something like this:

function createProductContentForAllFunctions(url, getThisData, container){
 return $.get(url, function(data){
    var products = [];
    $.each(getThisData, function(i, product) {
      var productHtml = '<div class="item">'+ product.title + '</div>'
      products.push(productHtml);
    });
    products.join('');
    container.html(products);
   });
  }

and then call the function something like:

function abc() {
 createProductContentForAllFunctions('url-to-a', data.bundle.products, '.bundle')
}

function xyz() {
 createProductContentForAllFunctions('url-to-different-location', data.search.products, '.search')
}

To be honoust I'm not sure where to start :) If I use the code in my example, so createProductContentForAllFunctions('url-to-different-location', data.search.products, '.search') I get errors like uncaught TypeError: cannot use 'in' operator to search for "length" in "product"

So my question is if it's even possible? Is it worth trying? And where should I start?

2
  • Have you tried it? If so, what did or did not happen? Yes, it is common to use functions to help abstract the code. Commented Oct 21, 2021 at 1:20
  • 1
    @PaulT.: Yes I tried several things one is like I did above. But that gives me errors obviously because data.bundle.products and data.search.products is nothing when running the getJSON function. It gives the error uncaught TypeError: cannot use 'in' operator to search for "length" in "product"... Commented Oct 21, 2021 at 6:53

2 Answers 2

2

You must provide all parameters you use in the function. Simply go this way:

function getProducts(url, mode, container) {
  $.getJSON(url, function(data) {
    var products = [];
    $.each(data[mode]products, function(index, product) {
      var productHtml = '<div class="item">'+ product.title + '</div>'
      products.push(productHtml);
    });
    products.join('');
    container.html(products);
  });
};
getProducts('/url1', 'bundle', $('.some-container1'));
getProducts('/url2', 'search', $('.some-container2'));

Please note:

Properties of JavaScript objects can also be accessed or set using a bracket notation. Objects are sometimes called associative arrays, since each property is associated with a string value that can be used to access it.

More about Working with JS Objects here.

Sign up to request clarification or add additional context in comments.

3 Comments

@skobajiic: Ok thx for your answer. But what @Shubham Raturi mentioned, the problem here is the index differs ocassionaly. So it can be something like data.products.search and data.bundle.products. But I could solve that with adding a second parameter called mode2 or something and make the each function looking for data[mode1][mode2]. So I'll accept your answer since this exactly what I'm looking for... Thx!!
It may be better to change your server side code and send request to the same url, than also send the mode via ajax and always get the result in same format. It looks like you've just copy/pasted the code to create the Search (but it could be implemented as a new mode in the old file). Thanks for the thumbs up, cheers!
Yes you are right! However it's build on a SaaS platform so I don't really have control over the supplied data and the format :) I'm satisfied with this solution you provided for now. Saves a few lines of code, thx!
0

This seems you have a different index in array search and bundle if it is possible to make them the same then it would be easier to handle in one function, if not then you can do like this.

abc('url-to-a','bundle');

function abc(url,type) {
  $.getJSON(url, function(data) {
    var dataArr;

    if(type=='search'){ // if type search then change the store search data
        var dataArr = data.search.products
    }
    elseif(type=='bundle'){ // if type bundle then change the store bundle data
        var dataArr = data.bundle.products
    }else{
        return "your message";
    }

    var products = [];
      $.each(dataArr, function(index, product) { // dataArr in each function
        var productHtml = '<div class="item">'+ product.title + '</div>'
        products.push(productHtml);
      });
      products.join('');
      container.html(products);
   });
 }

Thanks

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.