Open In App

How can I get the index from a JSON object with value ?

Last Updated : 22 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to learn how you get an index from a JSON object with value. we have given a value we need to search for that value with its key in the given JSON object and print the result in the console.

These are the following approaches:

Approach 1: Using the Array.find() method

In this approach, we are going to use the Array.find() method which is used to find the value in an array.

Example: In this example, we will use Array.find() to find the Index of the object.

Javascript




let data = [{
    "name": "HTML",
    "description": "HyperText Markup Language"
}, {
    "name": "CSS",
    "description": "Cascade Style Sheet"
}, {
    "name": "JS",
    "description": "JavaScript"
}]
let index = -1;
let val = "JS"
let filteredObj = data.find(function (item, i) {
    if (item.name === val) {
        index = i;
        return i;
    }
});
 
if (index == -1) {
    console.log("Data not found!")
} else {
    console.log(filteredObj.name, "is at index", index);
}


Output:

JS is at index 2

Approach 2: Using findIndex() method

In this approach, we are using the findIndex() method. This method is used to find the given value in an array and returns it’s index if the value is present in that array.

Example: In this example, we will use findIndex() method to find the Index of the object with “name”:”CSS”

Javascript




let data = [{
    "name": "HTML",
    "description": "HyperText Markup Language"
}, {
    "name": "CSS",
    "description": "Cascade Style Sheet"
}, {
    "name": "JS",
    "description": "JavaScript"
}]
let index = -1;
index = data.findIndex(obj => obj.name == "CSS");
 
if (index == -1) {
    console.log("Data not found!")
} else {
    console.log("Index is", index);
}


Output:

Index is 1

NOTE: The array.findIndex() method works similarly to array.find(), but it returns the index of the first element that matches the condition, rather than the element itself.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads