Open In App

JavaScript Program to Access Non-Numeric Object Properties by Index

Last Updated : 14 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, we can access non-numeric object properties by their keys (property names) rather than by index, as objects are not indexed like arrays. Objects use key-value pairs to store data. But there are certain ways to achieve this using the properties of the objects.

Approaches to access non-numeric object by Index in JavaScript

  • Using Object.keys() method
  • Using Object.values() method
  • Using Object.entries() method

Let’s explore the above possible ways to perform the accessing of non-numeric object properties by index.

Using Object.keys()

By using the Object.keys(obj) method, we will get the array of keys, which we will further use for extracting the data. We have defined a function that retrieves the values by using an index using the method Object.keys().

Example: Let’s see an example to demonstrate the above mentioned approach.

Javascript




let obj = {
    a: "abc",
    b: "cde",
    findByIndex: function (n) {
        return this[Object.keys(this)[n]];
    }
};
console.log(obj.findByIndex(1));


Output

cde

Using Object.values()

By using the Object.values(obj) method, we will get an array of values, which we will further use for extracting the data. We have defined a function that retrieves the values by using an index using the method Object.values().

Example : Let’s see an example to demonstrate the above

Javascript




let obj = {
    a: "abc",
    b: "cde",
    findByIndex: function (n) {
        let arr = Object.values(this)
        return arr[n]
    }
};
console.log(obj.findByIndex(0))


Output

abc

Using Object.entries()

By using the Object.entries(obj) method, we will get the array of each entry of the object, which we will further use for extracting the data. We have defined a function that retrieves the values by using the index using the method Object.entries().

Example : Let’s see an example to demonstrate the above

Javascript




let obj = {
    a: "abc",
    b: "cde",
    findByIndex: function (n) {
        let arr = Object.entries(this)
        return arr[n][1]
    }
};
console.log(obj.findByIndex(0))


Output

abc


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads