What techniques can be used to perform a complex JSON search in Javascript that involves multiple dimensions?

Currently, I'm in the process of developing a basic search system using JavaScript and JSON to fetch data stored within the JSON file. Within this file, multiple 'posts' are listed along with corresponding array of 'tags'. The primary objective is to filter through each post's tags and display only those matching a specific query, for example "funny cat video". To qualify for display, posts must encompass all three tags - "funny", "cat", and "video".

My main concern lies in achieving optimal performance outcomes. Given there are around 2000 posts with each bearing between 5 to 50 tags, executing this task solely through JavaScript may lead to inefficiencies. While seeking guidance on enhancing performance from various sources, additional assistance would significantly aid my progress.

Displayed below is part of the code detailing data storage:

{
    "index": {
        "count": "2",
        "posts": [
            {
                "id": "1",
                "date": "2014-11-21 17:16:39 GMT",
                "url": "http://url/",
                "image": "http://big_image/",
                "thumbnail": "http://little_image/",
                "tags": ["funny", "cat", "picture", "falling", "chair", "window sill", "funny"]
            },
            {
                "id": "2",
                "date": "2014-11-20 17:57:32 GMT",
                "url": "http://url1/",
                "image": "http://big_image1/",
                "thumbnail": "http://little_image1/",
                "tags": ["funny", "cat", "picture", "jumping", "water", "bath", "funny"]
            }
        ]
    }
}

Moreover, here is the existing JavaScript implementation:

var query = "funny cat bath".split(" ");
var data = JSON.parse("THE JSON GOES HERE");
var count = data.index.count;
var index = data.index.posts;
for (var i = 0, indexLength = index.length; i < indexLength; i++) {
    tags = index[i].tags;
    for (var q = 0, queryLength = query.length; q < queryLength; q++) {
        if(tags.indexOf(query[q]) !== false) {
            console.log(index[i]);
        }
    }
}

Regrettably, the current code fails to exclusively return posts containing all three specified tags and instead returns duplicates as well. Seeking an improved solution or alternative approach to overcome this roadblock. Any suggestions or guidance would be greatly appreciated!

Answer №1

To ensure that the match is only written out when all criteria are met, use a flag in your code. Currently, you are outputting the match as soon as one condition is found, which is not the intended behavior. Additionally, keep in mind that indexOf returns -1 if the item is not found, rather than returning false. See the basic concept illustrated below:

var data = {
    "index": {
        "count": "2",
        "posts": [
            {
                "id": "1",
                "date": "2014-11-21 17:16:39 GMT",
                "url": "http://url/",
                "image": "http://big_image/",
                "thumbnail": "http://little_image/",
                "tags": ["funny", "cat", "picture", "falling", "chair", "window sill", "funny"]
            },
            {
                "id": "2",
                "date": "2014-11-20 17:57:32 GMT",
                "url": "http://url1/",
                "image": "http://big_image1/",
                "thumbnail": "http://little_image1/",
                "tags": ["funny", "cat", "picture", "jumping", "water", "bath", "funny"]
            }
        ]
    }
};


var query = "funny cat bath".split(" ");
var matchingPosts = [];  
var posts = data.index.posts; 
for (var i=0; i<posts.length;i++) {  
    var post = posts[i];  
    var tags = post.tags;  
    var allCriteriaMet = true;  
    for (var j=0; j<query.length; j++) {  
        var index = tags.indexOf(query[j]);  
        if (index===-1) { 
            allCriteriaMet=false;  
            break;  
        }
    }
    if (allCriteriaMet) { 
        matchingPosts.push(post); 
    }
}
console.log(matchingPosts);  

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

Object Literal vs Object-Oriented Javascript: Comparing the Two

When it comes to using Object-Oriented Programming (OOP) in JavaScript, I often find myself not utilizing it much. For instance, instead of defining a constructor function and setting up prototypes like this: function Person(name){ return this.name = name ...

A loop that iterates through only the initial element of an array

When trying to call in the array values using the code snippet below, I encountered an issue. Upon clicking, I am able to successfully retrieve the first material in the array, but then it stops looping through the rest of the materials. Can someone plea ...

Navigating external pages with Vue Router

Could really use some assistance. I've got a JSON file filled with various URL links, some internal and some external. This is what the JSON structure looks like: [ {stuff..., "Url":"https://www.google.com/", stuff..}, {stuff... ...

Transforming Ajax POST requests into Angular 8 API calls

After receiving the Ajax Post call from the client, I was able to successfully insert static data when opening the PHP API file in a browser. Now, I am attempting to utilize Angular to achieve the same result. However, I am struggling to understand how to ...

Error SCRIPT438: The function 'formatCurrency' is not supported by this object

I'm encountering an "SCRIPT438: Object doesn't support property or method 'formatCurrency'"" error when attempting to format currency for cells within a jQuery datatable using the jQuery formatCurrency library. Below is the code snippe ...

Looking to implement pagination in Vue.js - what steps should I take?

Hi there, I'm currently facing an issue while trying to paginate my data. The error message in my console reads: Property or method "$index" is not defined on the instance but referenced during render. Below is my HTML template where I display the da ...

Utilizing Jquery for JSON Data Parsing

I have some JSON data that looks like this: {"product":["{productTitle=ABCD , productImage=/abcd.jpg, productPath=CDEF.html, productPrice=$299}","{productTitle=EFGH, productImage=xxxx.jpg, productPath=ggfft.html, productPrice=$299}"]} In my JSP page, I&a ...

Building forms within an AngularJS directive

I recently developed an AngularJS directive that includes a form. This form consists of a required text field along with two additional child forms. Each child form also contains a required text field. The distinguishing factor between the two child forms ...

Choose to either push as a single object or as individual items

I have a quick question that I'd like to get some clarity on. Can someone explain the distinction between these two code snippets: export const addToCart = function(product, quantity){ cart.push({product, quantity}); console.log(`${quantity} ...

Is it possible to eliminate the css class prefix when using Modular css in React?

When working with React & NextJS, I have observed that my modular SCSS files are automatically prefixing my classnames with the name of the file. Is there a way to turn off this feature as it is making the DOM structure difficult to interpret? For instanc ...

Is it possible to set custom spacing for specific breakpoints in a Material-ui theme?

Currently, I am in the process of ensuring that my Material-ui + React dashboard is responsive and well-styled for various screen sizes. Within my custom theme, I have set the spacing to 8: import { createMuiTheme } from '@material-ui/core/styles&ap ...

Converting from C# to JavaScript results in JSON decoding failing to capture a specific property

I am facing an issue with a c# object that I need to send to my JavaScript code. Although I can iterate over the items in the list, I am unable to access the string property ('Period'). When referencing the object in JS, no property is shown at ...

When using JSON.parse, a correct JSON string may unexpectedly produce a token error

This question has been asked several times before, but the answers provided did not help me. I have a JSON string that looks like this: var jsonData = { "target1": [ {"x":"222", "y":"333", "WPtext":"go right"}, {"x":"444", "y":"444", "WPtext":"go left"} ] ...

Utilizing JSON format for processing HTTP requests in JavaScript with Node.js

I'm working with a snippet that retrieves data in JSON format, but I'm interested in manipulating the data instead of just outputting it to the console. var request = require('request'); var headers = { 'Connection': ' ...

The values entered in the React form inputs are not displaying accurately

I'm currently working on a project that involves creating a form for tours. Everything seems to be working well, except for the issue of input values getting mixed up. For example: Actual output: { tourName: 'pune darshan', location: &apos ...

keeping the size consistent when submitting

I am currently developing a website that features several links on the side. When I click on one of these links, it redirects me to a specific .php file. Each PHP file contains the same header and footer. However, I have encountered an issue where every ti ...

What could be causing the child nodes of a particular class to not inherit the specified style?

When dynamically adding div child nodes to a search field, I do it like this: <div id="recommand" class="recommand"></div> data.result.forEach(function(entry) { let cont: rcommand; cont.username = entry[0]; const x = ...

JavaScript Array join() method returns an empty string

As a beginner in the world of javascript, I am just starting to dip my toes into it. In the past, I have used join() without any issues, but now I am facing a problem where this join is returning an empty string. Upon inspecting myArray, the data seems t ...

Adding elements to my state array - Utilizing Nextjs/React/Javascript

After fetching data from 2 different APIs that each return an object, I have stored them in separate states. Now, I want to merge these two objects into a single state that contains both of them as an array. However, when I try to do this, the second obj ...

Change a JSON Array into an HTML string that is wrapped using an Angular service

Currently, I am attempting to integrate a wysiwyg editor into my Angular application. The objective is to retrieve an array of objects by querying an endpoint, then format the data within each object based on its property name with different HTML tags. Fin ...