Searching for data within an array of objects that contain multiple key-value pairs in the form of arrays: A step-by-step guide

For instance

const information = [
    {
      companies: [
        {name: 'Yuri'},
        {name: 'Boeing'},
        {name: 'Laser'},
      ],
      sectors: [
        {name: 'Logistic'},
        {name: 'Aviation'},
        {name: 'Vocal'},
      ],
      location: [
        {name: 'Hong'},
        {name: 'Singapore'},
        {name: 'Switzerland'},
      ],
    },
  ];

If a search term like 'vocal' is entered, how do we locate and retrieve the corresponding value in the same structure?

Answer №1

This task should not prove too difficult.

Implement the reduce and filter methods.

Refer to the example provided below.

    const data = [
    {
      companies: [{
          name: 'Yuri'
        },
        {
          name: 'Boeing'
        },
        {
          name: 'Laser'
        },
      ],
      sectors: [{
          name: 'Logistic'
        },
        {
          name: 'Aviation'
        },
        {
          name: 'Vocal'
        },
      ],
      location: [{
          name: 'Hong'
        },
        {
          name: 'Singapore'
        },
        {
          name: 'Switzerland'
        },
      ],
    }];

    var searchText = "Vocal".toLowerCase();
    var result = data.reduce((arr, value) => {
      var item = {}
      const search=(key)=>{
          item[key] = value[key].filter(x => x.name.toLowerCase().indexOf(searchText) != -1);
      }
     search("companies")
     search("sectors")
     search("location")
     arr.push(item)
      
      return arr;
    }, [])

    console.log(result)

Answer №2

To efficiently search a JavaScript object, you can simply loop over and filter the data. Here is an example of how you can accomplish this: Search a JavaScript object

The process involves iterating through the data array and then iterating through each item to return the parent if it is found.

Answer №3

One approach to solving this problem is to iterate through your data and filter the entries based on their key while also ensuring a case-insensitive comparison by using .toLowerCase().

const data = [
  {
    companies: [
      { name: 'Yuri' },
      { name: 'Boeing' },
      { name: 'Laser' },
    ],
    sectors: [
      { name: 'Logistic' },
      { name: 'Aviation' },
      { name: 'Vocal' },
    ],
    location: [
      { name: 'Hong' },
      { name: 'Singapore' },
      { name: 'Switzerland' },
    ],
  },
];

const query = 'vocal'
let result = {}
Object.keys(data[0]).forEach(key => {
  data[0][key].filter(str => {
    if (str.name.toLowerCase() === query.toLowerCase()) {
      result = str
    }
  })
})

console.log(result) // { name: 'Vocal'}

Answer №4

To iterate through the keys of an object, you can utilize a for-in loop. To loop through an array of objects, you can make use of a for-of loop:

const data = [
  {
    companies: [
      {name: 'Apple'},
      {name: 'Google'},
      {name: 'Microsoft'},
    ],
    industries: [
      {name: 'Technology'},
      {name: 'Finance'},
      {name: 'Healthcare'},
    ],
    countries: [
      {name: 'USA'},
      {name: 'China'},
      {name: 'Germany'},
    ],
  },
];

function search() {
    let searchVal = document.getElementById('search').value.toLowerCase().trim();
    for (let key in data[0]) {
        for(obj of data[0][key]) {
            if(searchVal == obj.name.toLowerCase()) {
                console.log(obj);
                return;
            }
        }
    }
    console.log("Item not found.");
}
<input type="text" id="search" value="" />
<input type="button" value="Search" onclick="search()" />

Answer №5

Unclear about your specific request, but here is a method to recursively search for an object containing a specific case-insensitive string value within a nested object structure.

const findObject = (obj, str) => {
  for (const val of Object.values(obj)) {
    if (typeof val === 'object') {
      const result = findObject(val, str); 
      if (result !== undefined) return result;
    } else if (typeof val === 'string') {
      if (val.toLowerCase() === str.toLowerCase()) return obj;
    }  
  }  
};

findObject(data, 'word');    // { name: "Word" }

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

Having trouble with JSON parsing in Promise execution

I am in the process of developing a Promise with the objective of adding up any numbers discovered within an array or JSON object. The add() function is designed to receive a series of URLs as a string input and calculate the total sum of those URLs. Her ...

When submitting a form with the jQueryForm plugin, take action on the form by selecting it with `$(this)`

I have a situation where I have multiple forms on one page and am utilizing the jQuery Form plugin to manage them without having to reload the entire page. The issue arises when I need some sort of visual feedback to indicate whether the form submission wa ...

What can I do to prevent my panolens.js image from pausing its spin whenever a user clicks on it?

I've been working on setting up a 360 image background that rotates automatically and disabling most user interaction controls. However, I'm struggling with one issue – preventing any form of interaction from the user altogether. Whenever a use ...

Troubleshooting problems with Window.postMessage()

When attempting to fetch data from different domains, I am facing an issue. However, if I run the code on the same server, everything works perfectly fine and I am able to retrieve the message. index.html: <head> <title>Test 1</title&g ...

Creating an HTML5 video tag with bearer authentication using a WebAPI: The ultimate guide

My ASP.NET WebAPI requires bearer authentication, and most of my requests towards the API follow this format: GET http://localhost:29080/api/v1/users/me HTTP/1.1 Host: localhost:29080 Connection: keep-alive Accept: application/json, text/plain, */* Origin ...

The Object filter is experiencing a delay with processing 10,000 items

When an API returns over 10,000 objects in the format of {firstName:'john',lastName:'Cena'}, I am faced with a performance issue. In my parent React component, I make the API call in componentDidMount and pass this object to child compo ...

What causes the "This page isn't responding" error to pop up in Edge and Chrome browsers while attempting to perform consecutive tasks in a web application built with Angular 8?

Trouble with Page Loading Whenever this error occurs, I find myself unable to perform any activities on that page. The only solution is to close the tab and open a new one. My current code allows me to navigate through an array list (Next and Previous) us ...

What steps should I take to verify the validity of an Angular form?

I am struggling with validating an inscription form in HTML. Despite trying to implement validations, the inputs are still being saved in the database even when they are empty. Here are the validations I want to include: All inputs are required Email addr ...

Utilize Vue.js to take screenshots on your device

After following the tutorial at https://www.digitalocean.com/community/tutorials/vuejs-screenshot-ui, I was able to successfully capture a screenshot with Vue.js. However, it seems that the dimensions of the screenshot are not quite right. Issue: The cap ...

ReactJS - What is the best way to output a string from a functional component?

Utilizing @apollo/client in my React project for handling backend APIs. Within the file appollo.js, I am attempting to make a call to the backend API link based on certain conditions. Currently, appollo.js consists solely of functions and is not considere ...

Timeout of 30 seconds added to Axios network requests in Javascript

self.$axios .$get( `https://verifiedpro.herokuapp.com/getvmsstate?kiosk=${self.kiosk}` ) .catch(error => { console.log(error); location.reload(); }) .then(response => { console.log(respons ...

Converting JSON to PNG format using FabricJS

An image has been created and saved as fabricjs-json. Here is the link to the image: https://i.sstatic.net/7Wrhd.png Below is the json representation of the image: { "version": "5.2.1", "objects": [ { ...

Resolve the conflict with the upstream dependency when installing NPM packages

I'm encountering an issue while attempting to npm install vue-mapbox mapbox-gl - I keep getting a dependency tree error. Just to provide some context, I am utilizing Nuxt.js SSR with Vuetify and have not installed anything related to Mapbox before ru ...

Leveraging configuration files for HTML pages without any server-side code

I am currently working on developing an app using phonegap. At the moment, I have the reference to a script in every page like this: <script language="javascript" src="http://someServer/js/myscript.js"></script> If the server 'someServer ...

Program in C to determine the total number of elements in an array after elements have been inserted, excluding any counting while the elements

Seeking a solution in C programming language to calculate the number of elements in an integer array after inserting values, without counting during insertion. Is there an equivalent function for strlen() but for integer arrays? I am needing help in det ...

Different width, same height - images arranged side by side in a responsive layout

The problem lies in the images: https://i.sstatic.net/rydNO.png Here is an example of desktop resolution: https://i.sstatic.net/uv6KT.png I need to use default size pictures (800x450px) on the server. This means I have to resize and crop them with CSS to ...

Flattening nested arrays in Scala

Is there a way to flatten an array of nested arrays regardless of depth? For example val input = Array(1, Array(2,3), 4, Array(Array(5))) should be flattened to val output = Array(1,2,3,4,5) Appreciate any help on this. ...

What is the best way to import modules in Typescript/Javascript synchronously during runtime?

I have a Typescript class where I am attempting to perform a synchronous import, however, the import is being executed asynchronously. My code snippet looks like this: --------------100 lines of code-------------------- import('../../../x/y/z') ...

The clash between React Inline styles and Client CSS can lead to conflicts in styling

Our application needs to be loaded into the client's page, which is built using React. We are implementing React Inline Styles by defining styles as objects. However, we have encountered an issue where any CSS specified by the client using tag attribu ...

Angular Selectable Drop-down Menu

I'm facing an issue with using angularjs for dropdown with multiple selection. When I try to include 2 dropdowns in the same form, only one of them gets initialized properly. Here is a sample code snippet http://jsfiddle.net/vUSPu/1221/. Can someone p ...