Finding the complete object based on its index

Hey there, I'm looking to access a specific object in my JSON data by using an index. Can anyone guide me on how to do this? Here's a snippet of my JSON data:

[{
  "rec": ["act1","act2","act3"],
  "rec2": ["act11","act23","act4"]
}]

I'm aiming to retrieve the "rec2" object by passing the index 1. Any assistance would be greatly appreciated.

Answer №1

try using the Object.keys method

var data = [{
  "key1": ["value1","value2","value3"],
    "key2": ["value4","value5","value6"]
}];

data[0][Object.keys(data[0])[1]]

check out this example

Answer №2

If you want to retrieve a specific named index, you can experiment with the Object.keys() method in JavaScript:

var data = [{
    "first":  ["item1","item2","item3"],
    "second": ["item4","item5","item6"]
}];
var result = data[0][Object.keys(data[0])[1]];
console.log(result); // Output: ["item4", "item5", "item6"]

Answer №3

Here is a method to reach your goal.

let data = [{
  "category": ["category1","category2","category3"],
    "sub_category": ["subcat1","subcat2","subcat3"]
}]
let position = 2;

let categories = Object.keys(data[0]);

console.log(data[0][categories[position]]);

Answer №4

While not the most elegant solution, and not particularly efficient for accessing items with a large index,
the use of the Object.keys() method mentioned earlier is a better approach,
I have included this code snippet to demonstrate an alternative method.

var data = eval("[{\"rec\": [\"act1\",\"act2\",\"act3\"], \"rec2\": [\"act11\",\"act23\",\"act4\"]}]");
var index = 2;
var secondItem = null;
for (var key in data[0]) {
    if (--index === 0) {
        secondItem = key;
        break;
    }
}
alert(secondItem);

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

The JSON array successfully retrieves the data, however, it is unable to be formatted and displayed

I am having trouble displaying JSON data from an online source in my app. Although the data is being retrieved successfully, it does not appear on the activity where it should be displayed. I suspect there might be an issue with how I am populating the lis ...

trouble encountered when attempting to integrate typeahead functionality in AngularJS using jQuery

Greetings! I am brand new to using AngularJS and currently exploring the implementation of typeahead functionality. I decided to utilize an existing library by including the following script: <script src="lib/xyz/typeahead.bundle.js"></script> ...

A comprehensive guide to effectively formatting Recharts in React: addressing alignment and size management!

While attempting to style two graphs as floating cards, I am encountering difficulties in controlling the sizing and centering of the graphs. Specifically, I am having trouble with the pie chart in this example. To address this issue, I am passing paramete ...

The process of eliminating body padding in Nuxt.js

I'm considering building a website using Nuxt.js because I've heard it's both cool and user-friendly. While I do have some knowledge of vue.js, I'm stuck on a particular issue: How can I remove the padding from the body? I understand ...

Converting JSON data to CSV format

I have a goal of extracting JSON data from an API call and converting it into a CSV file. I am currently using sample code provided for the Yelp API at . Although I have managed to write the data into a CSV file, the formatting isn't ideal. I suspect ...

Having trouble with the application not launching on Heroku

I am facing an issue while trying to deploy my application on Heroku. Despite going through the troubleshooting and deployment procedures multiple times, I am unable to find a solution. I have been attempting to resolve this for the past 3 days. I have mad ...

How to utilize JS variables for filtering an array in EJS?

Is there a way to filter my user array based on the "username" variable in JavaScript? On the server side: var users = data.filter(u => u.id.startsWith('user_')).map(u => u.value); // [{"username": "arin2115", "som ...

Latest News: The store is now received in the mutation, instead of the state

An update has been made to this post, please refer to the first answer After thorough research, I couldn't find a solution to my issue despite checking several threads. This is my first time using the Quasar framework and it seems like I might have o ...

Refreshing content with Ajax when the back button is clicked

Hey everyone, I've been working on an ajax site and I'm having trouble getting the content to reload when the back button is clicked. I'm using Dynamic Drives ajax content script along with a script that changes the URL onclick and a popstat ...

Error: JSON parsing error due to attempting to access list indices with a string instead of an integer or slice

My goal is to retrieve and print at least one key value from the JSON that is returned. I'm following this basic tutorial for guidance. response=None booking_source = 'sourceBusinessName' api_request ='http://api.com' r = requ ...

Leverage the power of jQuery's .filter() method to pinpoint and target specific text

HTML: <p class="greeting"> hello, my name is kevin. what's yours? </p> jQuery: $("p.greeting").filter(function (){ return $this.text() === "my name is"; }).css("background", "green"); I am attempting to find and highlight the phra ...

Is there an Angular counterpart to Vue's <slot/> feature?

Illustration: Main component: <div> Greetings <slot/>! </div> Subordinate Component: <div> Planet </div> Application component: <Main> <Subordinate/> </Main> Result: Greetings Planet! ...

ES6 scoping confusion: unraveling the mystery

I stumbled upon these two syntax methods for exporting functions. Let's say we have files named actions.js and app.js. The first method looks like this: in actions.js export function addTodo() {} export function deleteTodo() {} and in app.js I have ...

What is the best way to record and share a video with jquery and laravel?

Is there a way to grant users access to record videos within an application and then upload them after previewing? I've been able to successfully record and download a video, but now I'm unsure of how to proceed with uploading it to the server. ...

The passport authentication process is currently stalled and failing to provide any results

The current authentication process is functioning properly app.post('/login', passport.authenticate('local-login', { successRedirect: '/home', failureRedirect: '/login', failureFlash: true }) ); Howev ...

Utilizing jQuery to dynamically pass parameters to the YouTube API

When making a request to the YouTube API, I am structuring it as follows: $.get("https://www.googleapis.com/youtube/v3/channels", { part: "contentDetails", id: "somestring", key: "MY-API-KEY" } /*, ...*/ ) A hidden field contains the value id ...

React components are failing to display data as expected

I need to display certain data based on the id provided in the url. When I use console.log() with res.json, I can see the data but I'm unsure how to pass it to the 'articleComponent'. const Articles = () => { const query = (id) => ...

How to pass a single value using onClick event without relying on form submission

I prefer to pass a single value instead of multiple putPriority fetch calls. This value will not be inputted by the user directly, but rather passed through an onClick event. For example, I want the onClick to send a specific number to "status" in the fe ...

Displaying PDF content in a new browser tab by utilizing JavaScript

Currently, I am utilizing the struts2 framework alongside dojo for the UI. My goal is to display a PDF in a new browser window. The PDF inputstream is obtained from the server through a standard AJAX call using the GET method (not utilizing a Dojo AJAX cal ...

Oops! Vue.js router configuration is throwing an error because it's unable to read properties of undefined when trying to access 'use'

Description: I have been working on a leaderboard web application using Vue.js. When I tried to launch the server on localhost after finishing my code, I encountered an error. The error message I received is as follows: Uncaught runtime errors: ERROR Cann ...