List of elements in JSON file with key value pairs and their indexes

Is there a way to create a function that can scan through a JSON file and identify the index where a specific key-value pair is located within an object? For instance, if we were searching for value: '100.0' in the following JSON data, the function should return 0 because the object with key1 is at index 0.

var object = {
    key1 : {
        name : 'xxxxxx',
        value : '100.0'
    },
    key2 : {
        name : 'yyyyyyy',
        value : '200.0'
    },
    key3 : {
        name : 'zzzzzz',
        value : '500.0'
    },
}

Answer №1

Check out this neat little code snippet:

http://jsfiddle.net/qskt9Lg9/

function findInJson(key1, value) { //use this function to find a specific key-value pair in JSON
    var i = 0;
    for (var key in object) {  
        var current = object[key];
        if (current[key1] == value) {
            return i; //return the index of the matching pair
        }
        i++;
    }
   return -1; //return -1 if no match found
}

To use the function, simply call it like this:

findInJson("name", "xxxxxx")

If you want to learn more about working with JSON arrays in JavaScript, check out this informative resource: .

Answer №2

If you are certain that a key in your object will not be removed and added back later, you can utilize the following function:

function findIndex(object, key, value) {
    var index = 0;

    for (var oKey in object) {
        if (object[oKey][key] === value) {
            return index;
        }

        index++;
    }

    return -1;
}

However, keep in mind that the for..in statement iterates over an object in an unpredictable order. Refer to the "Deleted, added or modified properties" section for a more detailed explanation.

If maintaining the order is important, consider using an array and incorporating "keyN" into your {name, value} object.

Answer №3

If you're looking to move away from supporting IE8 and older versions, consider using the Object.keys() method in your code:

function findIndex(value) {
    for (index = 0; index < Object.keys(dataObject).length; index++) {
        if (dataObject[Object.keys(dataObject)[index]].value === value) {
            return index;
        }
    };
    return -1;
};

console.log( findIndex("100.0") ); // returns  0
console.log( findIndex("500.0") ); // returns  2
console.log( findIndex("800.0") ); // returns -1

Check out this JSFIDDLE link for a live example.

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

Encountered an issue with a module not being found while trying to install a published React component library that is built using Rollup. The error message states:

In my latest project, I have developed a React component library called '@b/b-core' and used Rollup for building and publishing to the repository. When trying to install the library in a React app, an issue arises where it shows Module not found: ...

Trouble arises when trying to deploy React application on Github pages

After running npm run deploy and following all the steps, it shows that the project is published successfully. However, upon checking the Github hosted link, only my navbar component is visible. Despite setting up the routes correctly in app.js to display ...

Java ObjectMapper: Incorrect Dimensions in JSON Python Output File

Currently, I am extracting data from NLTK using Python and saving it to a file in JSON format so that I can later import it into Java. This is the code snippet I have in Python. wordcounts = nltk.ConditionalFreqDist((w.lower(), t) for w, t in brown.tagged ...

Please send the report in a designated JSON format

views.py This snippet of the views.py file retrieves phone information and converts it into JSON format before sending it back as a response. It loops through PhoneInfo objects associated with a specific user ID and constructs a dictionary for each phone ...

A guide on creating a Javascript leap year algorithm using Test-Driven Development techniques

Currently, I am working on crafting a leap year algorithm by utilizing a TDD suite. This marks my initial venture into the realm of TDD. Displayed below is the code extracted from the spec file. var Year = require('./leap'); describe('Lea ...

Compiling TypeScript into JavaScript with AngularJS 2.0

Exploring the capabilities of AngularJS 2.0 in my own version of Reddit, I've put together a script called app.ts ///<reference path="typings/angular2/angular2.d.ts" /> import { Component, View, bootstrap, } from "angular2/angular2 ...

Updating a field in Laravel based on a select input within a belongsTo relationship

After reading an article, I discovered a clever method for creating dynamic selection boxes. By making changes to routes/web.php, I was able to adapt it to suit my needs. Route::post('select-ajax', ['as'=>'select-ajax',&apo ...

Photos failing to load in the image slider

Although it may seem intimidating, a large portion of the code is repetitive. Experiment by clicking on the red buttons. <body> <ul id="carousel" class="carousel"> <button id="moveSlideLeft" class="moveSlide moveSlideLeft"></button& ...

How can I use the Jackson library to compare the structure of two JSON objects while ignoring their values?

I am currently utilizing the library org.codehaus.jackson. Within my code, I have two JSON objects. The first object is obtained from reading a file named hello.json, while the second object is generated automatically. Here is the structure of the first ob ...

Utilize AJAX to insert information into a MySQL database when a checkbox is selected

Before I got stuck here, I took a look at how a similar question was implemented here I attempted to implement the code in order to insert data into a MySQL database when a checkbox is clicked. While it may have been easier to do this on form submission, ...

Error: Unable to establish connection to server with docker-compose due to MongoError

Below is the contents of my docker-compose.yaml file: version: '3' services: app: image: chaseloyd/portfolio-site:latest ports: - "3000:3000" mongo2: image: mongo container_name: mongo2 restart: always ...

Resolved AWS S3 access issue with a 403 Forbidden error by eliminating the "ACL" parameter during upload

While working on the frontend using React.js, I utilized the Javascript SDK for file uploads to my S3 bucket with my AWS root account. Despite following the official documentation, I consistently received a 403 Forbidden error. To resolve this issue, if yo ...

What measures can I take to ensure a function is only executed once, even in cases where multiple change events are triggered simultaneously?

Individual checkbox clicks work smoothly without any issues. However, checking all checkboxes at once may cause problems when dealing with a large number of municipalities to loop through, leading to flickering in the dropdown and preventing users from sel ...

JSON objects within a loop may not consistently be present

I'm grappling with a complex JSON object that presents a challenge. The issue arises when certain elements within the JSON structure are missing, leading to errors in parsing and looping through the entire list. While some elements return complete da ...

Is the PHP array being reset and overwritten with each new ajax request?

With just one click of a button, an ajax POST is triggered to send data to my php script containing the following code: <?php $number = $_POST["id"]; $myarray[$number] = $_POST["marker"]; ?> The POST parameters used are id and marker. My ex ...

What is the best location in a Rails application to generate a JSON object?

I'm working on a Rails application that consists of two steps: 1) A form where users select various options. 2) A result table that displays output based on the selected options from step 1. Currently, the result table is built using datatables. Th ...

Can you point me in the right direction to find the Configure function within the EasyRTC module for

As a newcomer to NodeJS, I may be getting ahead of myself, but I'm diving into running the EasyRTC demo with NodeJS. On the EasyRTC download page, there are "easy install instructions" that outline the steps required to get EasyRTC up and running smo ...

What is the reason for requiring this to be passed as an Array instead of a String?

I'm currently learning node.js through a tutorial in a book titled Node Web Developments. Issue: I am struggling with understanding why an array [] is being passed as the 3rd argument from mult-node.js to the required function htutil.page(), instead ...

Adjust the navigation menu to display or hide as the page is being scrolled

Implementing an offset to display/hide the navigation menu when the page is scrolled 100px. Attempted to modify from lastScroll = 0 to lastScroll = 100 but it did not work as expected. Jquery: Fiddle // Script lastScroll = 0; $(window).on('scroll&ap ...

Using AngularJS $http.get method returns JSON with numeric keys, but we actually do not want any keys

Currently, I am conducting local testing on an AngularJS website. The issue I am facing involves parsing JSON data using the $http.get method from a local JSON file. When I manually define the JSON within my controller, everything works smoothly. However, ...