Searching for array items by a list of values using JSON and JavaScript

My JSON array looks like this:

[
    {
        French: 'Hello',
        Spanish: 'Hello1',
        english:'Hello2'
    },{
        French: 'Hello3',
        Spanish: 'Hello4',
        english:'Hello5'
    },{
        French: 'Hello6',
        Spanish: 'Hello7',
        english:'Hello8'
    },{
        French: 'Hello9',
        Spanish: 'Hello10',
        english:'Hello81'
    }
];

In a JavaScript array, I want to be able to search for items based on their values.

For example, if I input "Hello6" as the search string, I should retrieve the 3rd item in the list. I'm looking for a generic search function rather than having to manually search through each element.

Answer №1

Give this approach a shot:

function findIndex(arr, str) {
    for (var i = 0; i < arr.length; i++) {
        for (var key in arr[i]) {
            if (arr[i][key] === str) {
                if (arr[i].hasOwnProperty(key) {
                    return arr[i];
                }
            }
        }
    }
    return null;
}

This solution involves searching through an array using a traditional for loop, and then iterating over each element within the array with a for..in loop.

Answer №2

I have written a code snippet below that demonstrates the use of built-in functions:

let data = [/*your data sample*/];
let searchValue = "World7";

let filteredResult = data.filter(function (dataItem) { 
    return Object.keys(dataItem).some(function (key) { 
        return dataItem[key] === searchValue; 
    });
});

Answer №3

Here's a way to filter an array using the filter function:

var value = "Hello6";
// Filtering the array
filteredArray = jsonArray.filter(function(obj, index){
    for(var key in obj){
        if(obj[key] == value) return obj;
    }
});

var indexes=[];
// Finding the results
jsonArray.forEach(function(obj, index){
    for(var key in obj){
        if(obj[key] == value){
            indexes.push(index);
            break;
        }
    }
});

Answer №4

An efficient method to retrieve elements from an array is by using traditional for loops:

function searchArray(arr, func) {
    for (var index = 0, length = arr.length; index < length; index++) {
        if (func(arr[index]) === true) return arr[index];
    }
}

For example:

var array = [{ a: 1 }, { a: 2 }, { a: 3 }];
var result = searchArray(array, function (element) {
    return element.a === 2;
});
result; // { a: 2 }

If dealing with a more intricate array:

var array = [
    { a: 1, b: 2 }, 
    { a: 3, b: 4 }, 
    { a: 5, b: 6 }
];
var result = searchArray(array, function (element) {
    for (var key in element) {
        if (element[key] === 4) return true;
    }
});
result; // { a: 3, b: 4 }

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

There was a type error that occurred because the property 'addEventListener' could not be read from an undefined value

Encountering an issue with the JavaScript libraries three.js and OrbitControls.js despite following a tutorial: However, an error is being displayed in the console: Uncaught TypeError: Cannot read property 'addEventListener' of undefined at ne ...

The DIV element is failing to fill the entire screen's width

I am completely new to web development and currently working on creating my very first website. I've managed to set up the layout, but I'm facing an issue when trying to optimize it for mobile devices. Specifically, some of my divs (particularly ...

Convert the Java.util.Map into a JSON schema declaration

Struggling to find a simple solution, I'm looking to convert a java.util.Map instance into a JSON schema that can be recognized by the org.jsonschema2pojo Maven plugin in order to generate a POJO. I’ve hit a roadblock with this task and could reall ...

How do I check the value of a JavaScript variable in an XSL choose statement?

Currently, I am working with an xsl file in SharePoint and have implemented an xsl choose statement to conditionally display records from my xml. In the code snippet below, I am testing DAS_ID to determine if it is equal to *someValue*. While hardcoding a ...

What steps can I take to combine the values from an array of dictionaries?

Here is my current data: a = [{"country":"Colombia","date":"1995"}, {"country":"China","date":"1995"},{"country":"USA","date":"1992"}] ...

Explore an array of elements to find the correct objectId stored in mongodb

element, I am faced with a challenge of searching through an array of objects to find a key that contains nested object id for populating purposes. Exploring My Object { service: 'user', isModerator: true, isAdmin: true, carts: [ ...

Struggling to accurately determine the intersection face vertex positions in Three.js

Hello there! I've been immersed in the world of three.js, dealing with loading models using THREE.JSONLoader. Currently, I'm faced with the task of selecting these objects and their faces, which I've managed to do successfully. Now, my goal ...

Step-by-Step Guide: Unveiling a Particular Modal Post-Submission of Form with

My website has a form inside a modal, and when the form is submitted, I don't want the modal to close. However, I have encountered an issue because my SQL UPDATE statement redirects to the same page after updating the database. This disrupts the funct ...

Testing AG Grid's TypeScript in-line cell editing using Jest

I am currently working on writing Jest tests to evaluate the functionality of my ag-grid table. So far, I have created tests to check the default data in the grid and to test a button that adds an additional row of data to the grid. I am now attempting t ...

Error: The configuration property is not defined, causing a TypeError at Class.run ~/node_modules/angular-cli/tasks/serve.js on line 22

I'm encountering a persistent error on my production server that indicates a missing angular.json file, even though the file is present in the root of my project! Every time I run npm start, npm build, or npm test, I receive the same error message. ...

Utilize JQuery to easily share content with line breaks on WhatsApp

In order to properly share the content of a web page on WhatsApp using jQuery, I encountered an issue with text containing line breaks within the divblock3 element. <div class='divblock3'><p><p>Lorem Ipsum is simply dummy .<b ...

Tips for creating a new row in an Angular 2 template

Currently, I am delving into Angular 2. In my template, I have set up a code snippet to display data fetched from APIs: <div class="blocks"> <div router-active class="block" *ngFor="let item of items"> <div class="inblock"> & ...

Receiving a "Maximum call exceeded" error when using Vue.js router guards for the beforeEach hook

As I work on my Firebase-VueJS app, I am implementing basic security rules with router guards. In my main.js file, I have added the following code to handle permissions based on the user's authentication status. However, I encounter an error 'vue ...

What are the steps for launching a node.js application within vert.x?

I am completely new to vert.x and I am currently exploring the possibility of migrating an existing nodejs application to vert.x. At this point, I have followed the steps outlined in to install vert.x using npm. While I was able to run a simple hello-worl ...

Convenient methods in Three.js for easily detaching and attaching character weapons within a scene

I'm currently facing challenges while developing a first-person shooter game using Three.js. I've encountered major glitches with THREE.SceneUtils.detach() and THREE.SceneUtils.attach(), and I'm uncertain if they are the appropriate methods ...

Using jQuery and CSS to Filter and Sort Content

I need help with filtering a list of content based on their class names. The goal is to show specific items when a user clicks on one of two menus. Some items have multiple classes and users should be able to filter by both menus simultaneously. Currently ...

What are the steps to modify the sign in page on keystone.js?

I recently started using keystone.js and I'm having trouble locating the sign in page within the files. I've searched through all of the keystone.js files but can't seem to find where it's written. Can someone please guide me on how to ...

How can multiple functions be grouped and exported in a separate file in Node.js?

Is there a way to consolidate and export multiple functions in nodejs? I want to gather all my utility functions in utils.js: async function example1 () { return 'example 1' } async function example2 () { return 'example 2' } ...

Utilizing JavaScript variables to generate a custom pie chart on Google

Greetings! I must admit that I am a novice, especially when it comes to JavaScript. My background is mainly in PHP. Recently, I came across a fantastic pie chart created by Google https://developers.google.com/chart/interactive/docs/gallery/piechart I a ...

Navigating Perl: Unraveling the Mysteries of Accessing Hashes Within an

I have a unique Hash structure that I think refers to an array of hashes. I'm trying to figure out how to access the individual hash elements within this array. UPDATE: Here is the detailed hash structure $VAR1 = { 'CVE-2015-0677' =& ...