Looking through a Json file and retrieving data with the help of Javascript

I am currently working on developing a dictionary application for FirefoxOS using JavaScript. The structure of my JSON file is as follows:

[
{"id":"3784","word":"Ajar","type":"adv.","descr":" Slightly turned or opened; as, the door was standing ajar.","track":"a","track_2":"Aj","track_3":"Aja"},
{"id":"3785","word":"Ajar","type":"adv.","descr":" In a state of discord; out of harmony; as, he is ajar with the world.","track":"a","track_2":"Aj","track_3":"Aja"},{"id":"3786","word":"Ajog","type":"adv.","descr":" On the jog.","track":"a","track_2":"Aj","track_3":"Ajo"},
{"id":"3787","word":"Ajutage","type":"n.","descr":" A tube through which water is discharged; an efflux tube; as, the ajutage of a fountain.","track":"a","track_2":"Aj","track_3":"Aju"}                               ]

My current task involves querying this JSON file to find all entries where the word matches "aj" and retrieving the IDs associated with those results. How should I go about achieving this?

Answer №1

TRY THIS CHECK OUT THE UPDATED FIDDLE DEMO

var jsonArrr =[
{"id":"3784","word":"Ajar","type":"adv.","descr":" Slightly turned or opened; as, the door was standing ajar.","track":"a","track_2":"Aj","track_3":"Aja"},
{"id":"3785","word":"Ajar","type":"adv.","descr":" In a state of discord; out of harmony; as, he is ajar with the world.","track":"a","track_2":"Aj","track_3":"Aja"},{"id":"3786","word":"Ajog","type":"adv.","descr":" On the jog.","track":"a","track_2":"Aj","track_3":"Ajo"},
{"id":"3787","word":"Ajutage","type":"n.","descr":" A tube through which water is discharged; an efflux tube; as, the ajutage of a fountain.","track":"a","track_2":"Aj","track_3":"Aju"}                               ];

var matchMe = new RegExp('^' + 'aj', 'i');
    var matches = [];
        for (var i in jsonArrr) {
            if (jsonArrr[i].word.search(matchMe) > -1 ) {

                    matches.push( {'id': i, 'word': jsonArrr[i].word} );

            }
        }

To view the result

 for (var i in matches) { 
                console.log(matches[i].word);
                //your code
                }

Open the console window in Inspect Element to see the outcome

Answer №2

var matchedIndexes = []
for (var i=0; i < array.length; i++) {
    var obj = array[i];
    if (obj.hasOwnProperty("word")) {
        if(obj["word"].match(/aj/i)) {
            console.log("matched");
            matchedIndexes.push(i);     
        }
    }
}

matchedIndexes will store the indexes where the object contains the word "aj" in a case-insensitive manner. The array variable represents your set of arrays.

Answer №3

Iterate over the json array :

let targetObject = null;
    Objects.forEach(function(object, index){
        if(object.word == 'aj'){
            return targetObject = object;
        }
    });
    console.log(targetObject);

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

What is the best way to organize and group messages in JavaScript in order to push them to a subarray?

Having trouble coming up with a name for this question, but here's the issue I'm facing: I currently have an array in PHP containing several entries. Array ( [0] => stdClass Object ( [sender_id] => 0 [me ...

Encountering Syntax Error while running `ionic serve` in IONIC2

I'm stuck on this Syntax error and I can't figure out what went wrong. It keeps showing up even though I copied the code directly from the official ionic2 docs. SyntaxError: D:/Manson/Arts/Ionic/IonicTodo2/app/pages/list/list.js: Unexpected toke ...

Is it possible to establish role-based access permissions once logged in using Angular 6?

Upon logging in, the system should verify the admin type and redirect them to a specific component. For example, an HOD should access the admi dashboard, CICT should access admin2 dashboard, etc. Below is my mongoose schema: const mongoose = require(&apo ...

Updating the background image without having to validate the cache

I have implemented a basic image slideshow on my website using a simple Javascript function. The function runs every 5 seconds to update the CSS "background-image" property of a div element. While it is functional, I've noticed that each time the func ...

Why is "undefined" being used to alert an ajax call response?

I am encountering an issue with a returned value from an AJAX request. The web method being referenced returns a boolean value of true or false. However, when attempting to access this value outside the AJAX method, I am receiving an "undefined" message :? ...

The issue with Google Maps API not loading is being caused by a problem with the function window.handleApiReady not being

Having trouble with the Google Maps API, specifically encountering an error during page load that says window.handleApiReady is not a function, even though it definitely exists. Examining the code snippet below reveals its usage as a callback function: ...

The JavaScript code is failing to retrieve any data from the API

import React, { Component } from 'react'; export class FetchData extends Component { static displayName = FetchData.name; constructor(props) { super(props); this.state = { users: [], loading: true }; } componentDidMount() { ...

Is it a guarantee that a function called in the head section of a JavaScript for-of loop will only be executed once?

In both Firefox and Chrome, I tested the code snippet below: function test() { console.log("***") return [1,2,3] } for (const t of test()) { console.log(t) } After running this code, I noticed that the test function was only called once. T ...

How can I trigger an Iframe JavaScript function from within my webpage?

I have an Iframe within my page, with the following JavaScript code: function getTotSeats(){ window.WebAppInterface.showToast(document.forms[0].txtSeat_no.value); return document.forms[0].txtSeat_no.value; } I would like to call the above Jav ...

The issue persists with the Javascript AJAX POST Method as it fails to transmit values to the designated

I have been using Javascript AJAX to make a request to a php page and receive the output from that page. Interestingly, when I use the GET method in my AJAX call, everything works as expected. However, the issue arises when I try to use the POST method. B ...

json remove unnecessary detailed timestamps

I need to develop a service that only returns JSON with date, time, and minutes, but the current implementation is displaying everything including milliseconds and seconds in the timestamp. How can I remove the milliseconds and seconds from the output? Be ...

NodeJS guide: Enabling cross-domain access for web services

Currently, I am developing a nodejs server and facing the challenge of needing to access additional services through ajax from a different domain. Can anyone provide guidance on how to bypass the cross-domain restriction within nodejs code? Please note th ...

Making changes to HTML on a webpage using jQuery's AJAX with synchronous requests

Seeking assistance to resolve an issue, I am currently stuck and have invested a significant amount of time. The situation at hand involves submitting a form using the traditional post method. However, prior to submitting the form, I am utilizing the jQue ...

Utilize .NET and C# to extract data from a JSON response sent by a Webhook

I've been attempting to grasp the concept of deserialization without much success. Despite trying various examples, I can't seem to figure out how to deserialize the JSON response from a Webhook provided below. Any guidance on this matter would b ...

Ways to conceal a div element when the JSON data does not contain a value

If the value in "desc" is empty, then hide <div24> and <popup-desc>. html <div class="popup"> <div class="popup-top" style="background-color: '+e.features[0].properties.fill+';"> ...

Error decoding JSON response during an ExtJS 4 AJAX request for plain text content

Here is the code snippet: Ext.Ajax.request({ url: 'modules/tags.cfc?method=getHtml', success: function(response, opts) { //var obj = response.responseText; console.dir(response, opts); ...

Tips for automatically choosing several choices from a multiple-select using Chosen.JS

I am struggling to programmatically select multiple values in a multiple select using chosenJS/chosen.js while still ensuring that the selected values are bound to my ng-model (angularJS). In this scenario, I have a list of users, some of whom are already ...

Dynamic urls from previous getJSON calls are utilized in nested getJSON calls

I am seeking assistance in finding a more dependable method for accomplishing this task. We are working with 3 fixed URLs that cannot be modified. The process begins with a getJSON call to url1 to retrieve all the sections. Within the callback function ...

Executing multiple nested $http calls in Angular can significantly slow down the process

Within my angular application, I am currently dealing with 6 to 7 http chaining requests that are taking a significant amount of time to execute. What are some strategies for optimizing this process? empSvc.getallEmp().then(function (data) { if (dat ...

Navigating a table while keeping headers in place at the top

Trying to construct a table where the thead remains fixed while the tbody scrolls. Utilizing percentages and fixed width for cell size determination, aiming for uniformity and alignment between percentage td's and thead headers. Referenced JSFiddle d ...