Explore all sorts of data such as search term within a JavaScript JSON array

In my JSON array of objects, I have data displayed in an HTML table. Above the table, there is a search input where users can enter search terms.

[
{
"id": 1,
"title": "My fridge door closed",
"description": "The fridge door was closed yesterday.",
"point": 8989,
"user_id": 4,
"created_at": "2019-11-23T19:54:46.000Z",
"updated_at": "2019-11-23T19:54:46.000Z",
"deleted_at": null
},
{
"id": 4,
"title": "Miu Miu Inc",
"description": "Closing doors for maintenance.",
"point": 6767,
"user_id": 6,
"created_at": "2019-11-23T19:58:08.000Z",
"updated_at": "2019-11-23T19:58:08.000Z",
"deleted_at": null
}
]

I would like to implement search functionality where users can search the table for any term or substring from the JSON array above and retrieve the object that includes the searched term.

For example, if a user types 'pl' into the search input, all objects containing that term should be returned.

Answer №1

Utilize the Object.values method to access all values and apply a combination of the filter function along with the some method to check if a specified string is present as a substring using the includes approach:

const data = [
{
    "id": 1,
    "title": "my frig closed",
    "description": "closed frig pla ola pla",
    "point": 8989,
    "user_id": 4,
    "created_at": "2019-11-23T19:54:46.000Z",
    "updated_at": "2019-11-23T19:54:46.000Z",
    "deleted_at": null
},
{
    "id": 4,
    "title": "miu you inc",
    "description": "closed frig pla ola pla",
    "point": 6767,
    "user_id": 6,
    "created_at": "2019-11-23T19:58:08.000Z",
    "updated_at": "2019-11-23T19:58:08.000Z",
    "deleted_at": null
}
];

let phrase = "pl";

let result = data.filter(
    obj => Object.values(obj).some(
       val => typeof val === "string" && val.includes(phrase)
    )
);

console.log(result);

Answer №2

One approach is to create an object that contains the necessary functions and data, followed by adding a lookup function. This method remains effective even in older browsers such as IE 6 and maintains good speed. Additional features like lookup and lookupAny are included along with a few examples.

let myObjects = [{
    "id": 1,
    "title": "my frig closed",
    "description": "closed frig pla ola pla",
    "point": 8989,
    "user_id": 4,
    "created_at": "2019-11-23T19:54:46.000Z",
    "updated_at": "2019-11-23T19:54:46.000Z",
    "deleted_at": null
  },
  {
    "id": 4,
    "title": "miu you inc",
    "description": "closed frig pla ola pla",
    "point": 6767,
    "user_id": 6,
    "created_at": "2019-11-23T19:58:08.000Z",
    "updated_at": "2019-11-23T19:58:08.000Z",
    "deleted_at": null
  }
];

var myApp = myApp || {};
myApp.functions = {
  indexOf: function(myArray, searchTerm, property) {
    for (var i = 0; i < myArray.length; i++) {
      if (myArray[i][property] === searchTerm) return i;
    }
    return -1;
  },
  indexAllOf: function(myArray, searchTerm, property) {
    var ai = [];
    for (var i = 0; i < myArray.length; i++) {
      if (myArray[i][property] === searchTerm) ai.push(i);
    }
    return ai;
  },
  lookup: function(myArray, searchTerm, property, firstOnly) {
    var found = [];
    var i = myArray.length;
    while (i--) {
      if (myArray[i][property] === searchTerm) {
        found.push(myArray[i]);
        if (firstOnly) break; //if only the first 
      }
    }
    return found;
  },
  lookupAny: function(myArray, searchTerm, property, firstOnly) {
    var found = [];
    var i = myArray.length;
    while (i--) {
      if (myArray[i][property].indexOf(searchTerm) !== -1) {
        found.push(myArray[i]);
        if (firstOnly) break; //if only the first 
      }
    }
    return found;
  },
  lookupAll: function(myArray, searchTerm, property) {
    return this.lookup(myArray, searchTerm, property, false);
  },
  remove: function(myArray, searchTerm, property, firstOnly) {
    for (var i = myArray.length - 1; i >= 0; i--) {
      if (myArray[i][property] === searchTerm) {
        myArray.splice(i, 1);
        if (firstOnly) break; //if only the first term has to be removed
      }
    }
  },
  removeByIndex: function(myArray, index) {
    myArray.splice(index, 1);
  }
};

// exact
let term = "my frig closed";
let propertyName = "title";
let firstOnly = true;
let weFound = myApp.functions.lookup(myObjects, term, propertyName, firstOnly);
console.log("match:", weFound);
// a partial
let partterm = "pla";
propertyName = "description";
firstOnly = false;
let weFoundPart = myApp.functions.lookupAny(myObjects, partterm, propertyName, firstOnly);
console.log("match Contains:", weFoundPart);

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

In MongoDB and Node.js, encountered error: 'Unable to access property 'collection' as it is undefined'

I'm encountering a type error with my collection function that was previously functioning without any issues. This code was working perfectly in another project of mine. After reusing a lot of the code, I started experiencing this error. My MongoDB c ...

Error encountered in loop for concatenating html elements: identifier unexpectedly found (jquery + html + php)

I am attempting to concatenate HTML inside a variable within a loop and then return it populated. However, I am encountering an error: Uncaught SyntaxError: Unexpected token += in my code. <a style="cursor: pointer" id="addmore">More Entree ?</ ...

Add three rows without clicking, then click once to add one row at a time

Seeking guidance on how to defaultly display 3 rows after adding and removing rows, as well as applying the removal of a default set of 3 rows using JavaScript. Any valuable ideas are appreciated! Example needed:- https://i.sstatic.net/DF8Wn.png $(docum ...

Troubleshooting Bootstrap: Navigation bar toggling causes JS functions to malfunction

My JS function is no longer working when the responsive website's breakpoint of 768px is activated (specifically, the nav var toggle/collapse). This is causing the problem where the JS function stops working. The HTML code in question is: <div cl ...

What could be the reason for PhantomJS getting stuck when jQuery is invoked?

Currently, I am using PhantomJS 2.0.0 on a Mac OS X Yosemite: $ phantomjs --version 2.0.0 The script I have attached below seems to get stuck at the line where it calls $('h1').size(): system = require('system'); function usage() { ...

Retrieve data from Postgres by searching for multiple array elements within each row and returning them as JSON

I need to extract all subscriptions with an interval of "1 WEEK" from the 'data' column provided below: [ { "id": "tran_6ac25129951962e99f28fa488993", "amount": 1200, "client": { "id": "client_622bdf4cce2351f28243", "su ...

Parsing JSON arrays in C# and extracting specific values

Having some trouble parsing this json array: I'm looking to extract specific values for each timestamp, such as close, high, low, and open. I've experimented with different methods that have worked with simple json strings, but I'm struggl ...

Parse JSON files from a folder and concatenate them to a CSV using Node.js

Thank you for offering your help. I have a collection of JSON files located in a directory with unknown names. I need help with the following: (1) Reading all the JSON files (2) Appending the data from the JSON files to output.csv (3) Adding "-Appended" t ...

The ng-View feature appears to be malfunctioning within AngularJS

I'm extremely new to AngularJS and am having trouble with ng-view. Here is the code from AngularFormsApp.js: var angularFormsApp = angular.module('angularFormsApp', ["ngRoute"]); angularFormsApp.config(function ($routeProvider) { $routeP ...

Search for objects in the array that have the same name, and then combine the values of those matching

I've done some research on various platforms, but haven't come across a solution to my specific issue. I'm looking to extract objects from an array and group them by their names in order to calculate the total hours for each matching object. ...

Tips for labeling subplots in PLOTLY JS

Looking for some guidance on adding titles to plots in Plotly JS. I've checked out the documentation but couldn't find anything helpful. Any tips or suggestions would be greatly appreciated! ...

The supplied parameters do not correspond with any valid call target signature for the HTTP delete operation

I've been attempting to utilize the http delete method in Angular 2, but I keep encountering a typescript error: Supplied parameters do not match any signature of call target.. Below is the code I am using: let headers= new Headers(); ...

How to round whole numbers to whole numbers using JavaScript?

Looking to manipulate some numbers in JavaScript. Let's say we have x = 320232, y = 2301, and z = 12020305. The goal is to round these numbers to the nearest tens, hundreds, or thousands place. Thus, we want them to become x = 320000, y = 2300, and z ...

Encountering a "Connection Refused" error when attempting to test a React and Express application

Currently, I am developing an order system using React for the frontend (port 3000) and Express for the backend (port 3001). Everything functions perfectly when tested on the same MacBook that hosts the node project. However, when testing it on a differen ...

How can a TypeScript function be used to retrieve a string (or JSON object)?

When attempting to retrieve data from a web API using TypeScript and return the JSON object, encountering an error has left me puzzled. Inside my function, I can successfully display the fetched data on the console, but when I try to return it with return ...

Tips for effectively generating a JSON object array in Typescript

Currently, I'm attempting to construct an array of JSON objects using TypeScript. Here is my current method: const queryMutations: any = _.uniq(_.map(mutationData.result, function (mutation: Mutation) { if (mutation && mutation.gene) { co ...

Discover the final index of an array with Angular's ng-repeat functionality

I'm currently working with an Object that contains array values which I am trying to iterate over. Here's a simplified example of what I have: $scope.messages = { "1": [ { "content": "Hello" }, { "content": "How are you" }, { "conte ...

Ways to extract specific text from a JSON object's content

Working with React JS and JSON data, I have a timestamp that includes both date and time. For example: "timestamp":"2020-03-23T14:00:00.000Z" When creating a chart using Chart.js, I only want to display the date (e.g., 2020/03/23 instead of 2020-03-23) w ...

Top eCommerce frameworks optimized for Web2 and SaaS integration

Are there any payment and eCommerce frameworks that can seamlessly integrate with a REST-based application right out of the box? My server is Java-based, but I've found limited options in this area. I'm open to wrapping my interface with another ...

Guide on utilizing getelementsbytagname for retrieving LI values

As I attempt to locate a specific product on amazon.com, my goal is to extract the ASIN for each item. This particular code snippet runs through various search options and retrieves the price of each product from Amazon one by one. However, in addition to ...