Iterating through a JSON dataset of various clothing items to search for a specific keyword within the product titles

$(function() {
$.getJSON('test.json', function(data) {
  for (var i = 0; i < data.products.length; i++) {
    var obj = data.products[i];
    if (obj.title.toLowerCase().includes("t-shirt")) {
      var Imgs = '<div class="Tops"><img src="' + obj.imUrl + '"></div>'
      $(Imgs).appendTo($(".TopsImages"));
    }
      var bought_together_id = obj.related["bought_together"];
      if (obj.asin in bought_together_id) {
        if (obj.title.toLowerCase().includes("sandal")) {
          var Imgs = '<div class="Shoes"><img src="' + obj.imUrl + '"></div>'
          $(Imgs).appendTo($(".ShoesImages"));
        }
      }
    }
  })
})
  • asin = ID
  • imUrl is the image field where the image url is saved

To elucidate my JavaScript code, I am utilizing a loop to iterate through every product and its data from a JSON file. My objective is to analyze each product individually.

I have succeeded in reading the title field of the product and then checking if it contains "t-shirt", "hat", "pants/jeans" or "shoes". Subsequently, displaying the 'imUrl' value of the product in the appropriate div class such as TopsImages, PantsImages, ShoesImages, or HatsImages.

The challenging part arises when attempting to scrutinize the 'bought_together' field values of the same product one at a time, which are three different IDs of three distinct products. The goal is to identify the data for the IDs, examining if the title field of that product includes "t-shirt", "hat", "pants/jean" or "shoes", and exhibit the 'imUrl' value accordingly in the relevant div class like TopsImages, PantsImages, ShoesImages, or HatsImages.

This process repeats for the other two bought_together product IDs until a complete outfit is formed. Moreover, there will be arrows pointing left and right, enabling the user to navigate between products by clicking on them.

In summary, after retrieving the 'bought_together' list of IDs from the product data, I encounter difficulties in pinpointing the product that corresponds to the ID within the JSON file sequentially.

The snippet of my code where I am trying to achieve this is: obj.asin in bought_together_id, however, it solely verifies the first product's ID instead of evaluating the entire JSON file.

var bought_together_id = obj.related["bought_together"];
if (obj.asin in bought_together_id) {
    if (obj.title.toLowerCase().includes("sandal")) {
        var Imgs = '<div class="Shoes"><img src="' + obj.imUrl + '"></div>'
        $(Imgs).appendTo($(".ShoesImages"));
    }
}

Here is an excerpt of my JSON file showcasing the structure I am working with. It consists of about ten similar snippets representing ten unique products.

{
  "products": [{
    "asin": "B0001MQ60A",
    "title": "KEEN Men's Newport H2 Sandal",
    "imUrl": "http://ecx.images-amazon.com/images/I/41pRaO7fFSL._SX395_.jpg",
    "related": {
      "also_bought": ["B000MN8OR6"],
      ...
  }]
}

Additionally, here is the HTML markup connected to the rest of the code, featuring four empty divs allocated for different types of clothing:

<article class="column large-2">
    <div class="HatsImages">

    </div>
    <div class="TopsImages">

    </div>
    <div class="PantsImages">

    </div>
    <div class="ShoesImages">

    </div>
</article>

Answer №1

I believe the correct way to write it is

if (bought_together_id.indexOf(obj.asin) > -1) {

console.log(obj.asin in bought_together_id); -> false
console.log(bought_together_id.indexOf(obj.asin) > -1); -> true

Please note that I could not find any documentation on using "String in Array"; such as obj.asin in bought_together_id

Answer №2

There appears to be a problem with your if statement on line #11(if (obj.asin in bought_together_id) {)

You can try the updated code below,

$(function() {
$.getJSON('test.json', function(data) {
    var jsonData = JSON.parse(data);
  for (var i = 0; i < jsonData.products.length; i++) {
    var obj = jsonData.products[i];
    if (obj.title.toLowerCase().includes("t-shirt")) {
      var imageTag = '<div class="Tops"><img src="' + obj.imUrl + '"></div>'
      $(imageTag).appendTo($(".TopsImages"));
    }
      var bought_together_id = obj.related["bought_together"];
      if (bought_together_id.indexOf(obj.asin)  >=0) {
        if (obj.title.toLowerCase().includes("sandal")) {
          var imageTag = '<div class="Shoes"><img src="' + obj.imUrl + '"></div>'
          $(imageTag).appendTo($(".ShoesImages"));
        }
      }
    }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The execution of async.each does not complete successfully

I'm facing an issue with a simple function that retrieves the word count from a URL. The script runs smoothly with a low number of URLs, limiting the async to 4 at a time. I keep an eye on my RAM and CPU usage, but they never come close to maxing out. ...

New feature alert! Introducing the Mentio JS menu now available at the bottom of the webpage

I am currently working on creating a Twitter-style @mention feature using Angular JS and a library called MentioJS. One issue I encountered is that after dynamically adding content to the page, a mysterious menu appears at the bottom of the page. This pro ...

What is the process for determining the overall cost of a column in Angular 9?

I am facing a challenge in calculating the total price, total quantity, and total counted(#) of each column in a table. | Item | Price | Quantity | 1 | Mouse | 500 | 1 | 2 | Wire | 100 | 2 | TI:3 | |TP:600 | TQ:3 | < ...

The functionality of activating a button is not functioning as expected in AngularJS framework

Next to the question I have linked here, I am exploring a different approach. As a beginner in AngularJS/Cordova/Ionic, my goal is to achieve different outcomes when the "Eingepasst" button is clicked, each with unique logic compared to "Gewonnen" or "Ver ...

Expanding properties in a React component based on certain conditions using TypeScript

I am attempting to dynamically expand my component props based on whether a specific prop is included. The goal is to add attributes from an anchor if the href prop is provided, and include attributes from a button if it is not. Is this achievable? Chec ...

Ways to retrieve an input field value without triggering form submission

I'm currently working on a payment form where users input the amount in a text field. I also have another text field on the same form that should automatically display the amount in words based on the user input. However, I'm struggling to figure ...

An error has occurred in Node.js: SyntaxError - Unexpected token ]

Here is the code snippet I am working with: app.get("/posts/:slug", function(request, response) { var slug = request.params.slug; connection.query("SELECT * from `posts` WHERE slug = ?", [ slug ], function(err, rows) { var post = rows[]; ...

What is the best way to utilize functions from different JavaScript files?

I'm currently handling server-side javascript and I've got confidential data that needs to remain secure, stored in a private directory. If I choose to enclose this data within a function, how can I go about invoking that function from a separate ...

Steps for inserting a button within a table

Currently, I have implemented a function that dynamically adds the appropriate number of cells to the bottom of my table when a button is clicked. This is the JavaScript code for adding a row: <a href="javascript:myFunction();" title="addRow" class= ...

The error occurred in JSON.java at line 107: org.json.JSON.typeMismatch

My Code Below: public class JSONActivity extends Activity { TextView json; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); String twitt ...

What is the best way to transform a valuesqueryset into a JSON object that includes datetime information?

Hey there! I'm currently working on converting a list to JSON, and here's the code I'm using: json.dumps(myList) However, I've run into a little hiccup with some datetime values in my valuesqueryset... Any thoughts on how to tackle t ...

Identify when a user switches tabs within the browser and when they switch applications away from the

I am interested in understanding the behavior of the tab's visibility state when a user switches tabs in a specific browser and when they switch out of the application entirely (switching away from the browser). var visibilityState, activeTab = ( ...

The Chrome application does not retain cookies

Why is the cookie url_user not being stored? Below is the content of index.html: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial- ...

When I close all of my tabs or the browser, I aim to clear the local storage

Could you recommend any strategies for clearing local storage upon closing the last tab or browser? I have attempted to use local storage and session storage to keep track of open and closed sessions in an array stored in local storage. However, this meth ...

how to put an end to sequential animations in React Native

Is there a way to pause a sequenced animation triggered by button A using button B? Thank you for your help! ...

Personalized path-finding tree iterator

I am trying to implement a custom iterator in JavaScript that can traverse a DOM tree based on specific criteria provided by a callback function. The goal is to return an array of the nodes that match the criteria as the generator iterates through the tree ...

Retrieve information using the useEffect hook on a server-side rendered webpage

I am currently working on a project using React JS and Next JS. The page is dynamic, utilizing getStaticPaths and getStaticProps to fetch most data on the server side for rendering. However, there are certain pieces of data that require a token stored in l ...

remove website tracking data by using developer tools console

In JavaScript, we have the ability to delete local storage or session storage items using the clear() method: localStorage.clear(); sessionStorage.clear() However, is there an equivalent method like cookies.clear() to clear cookies? If so, how can it be ...

The mathematical logic behind navigating forward and backward in Angular

Calling all math experts! I need your help with a slider issue. The prevSlide function is working perfectly, but the nextSlide function seems to be starting off on the wrong foot. It goes 1-2-3 and then jumps to 2-3-2-3... It's definitely a math probl ...

What is the method to determine the index of a removed element within a subarray?

In my array, all = [2,3,4,12, 55,33], there is a sub-array named ar1 = [12, 55, 33] starting from the value 12. If I remove a value from all that is present in ar1 (e.g. 12), how can I determine the index of this value in ar1 (0 for 12) so I can also remo ...