Getting the key of a JSON object within the object itself while using a Vue v-for loop in JavaScript

I am not interested in the keys that are contained within this object, but rather the key of the object itself (the key in the array holding the object).

Here is the JSON data I am working with:

{
    "Object name (text)": {
        "raw": "Some more text.",
    },
    "Another name": {
        "raw": "Some other text.",
    }
}

and what I want to achieve is to retrieve "Object name (text)" for the first item.

This is my Vue code snippet:

<CustomComponent
    v-for="object in objects"
    :key="getKey(object)"
    :object="object"
/>

I'm unsure if using the getKey function to get unique identifiers for iterating through the JSON array is the correct approach. The current code for getKey method looks like this:

getKey(object) {
   return Object.keys(object)[0];
}

Now, my aim is to somehow pass the name of the object to the CustomComponent ("Object name (text)" in this case).

One temporary solution I thought of was extracting the keys from the objects array in this way:

:objectName="getObjectName(object)"
and initializing itemNumber: -1 in the data along with this method:

getObjectName(object) {
   this.itemNumber = this.itemNumber + 1;
   var objectName = Object.keys(this.objects)[this.itemNumber];
   console.log("Object name: ", objectName);
}

However, I noticed that the first line in the getObjectName method causes it to run multiple times instead of just twice (any reason for this?; it only happens in the first two executions of the method or when excluding that line), and I don't believe this is the proper way to simply fetch the object's name/key.

When I tried integrating the above code into the getKey method, which appeared to make more sense (initially I had it there before moving it to a separate method for debugging purposes), accessing the key in the component with this.$vnode.key didn't work as it remained undefined. This issue might be distinct even though it could potentially solve the problem at hand - I may consider opening a new inquiry about it. Both the "getKey" and "getObjectName" methods are being called six times each despite rendering only two items on the page, as expected.

-> How can I extract the key of a JSON object in JavaScript?
(Preferably directly from the object itself after iteratively going through a JSON array using Vue's loop, rather than indirectly by inspecting the objects array.)

Edit: as a temporary fix, I have implemented the following:

var keys = Object.keys(this.objects);
    keys.forEach(element => {
      this.objectsWithKeys.push({
        object: this.objects[element],
         key: element
      });
    });

<CustomComponent
   v-for="objectWithKeys in objectsWithKeys"
   :key="objectWithKeys.key"
   :object="objectWithKeys.object"
>
</CustomComponent>

this.$vnode.key

Answer №1

The problem has been resolved by implementing the code

var objectsWithKeys = data[Object.keys(data)];
along with {{ $vnode.key }}.

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

There seems to be an issue with the audioElement.src, which I used to run and play different songs. However, it is now displaying a 404

Array.from(document.getElementsByClassName('songItemPlay')).forEach(function (item) { item.addEventListener('click', (evt) => { playAllSongs(); position = parseInt(evt.target.id); evt.target.classList.re ...

import an external JavaScript file in an HTML document

Looking to load a .js file from a simple HTML file? If you have these files in the same folder: start.js var http = require('http'); var fs = require('fs'); http.createServer(function (req, response) { fs.readFile('index.htm ...

show a blob within an image element using JavaScript

I have a blob file retrieved from mySql and it looks like the image you see below. https://i.sstatic.net/DkLbh.png Now, I want to display this image using the <img src={imagefile}/> tag in React.js. How can I convert the blob file to a URL link? I ...

Organizing outcome searches through ajax

I have a result table displayed on the left side https://i.stack.imgur.com/otaV4.png https://i.stack.imgur.com/pp9m0.png My goal is to transform it into the format shown on the right side of the table In a previous inquiry found here, @Clayton provided ...

The 'ReactType' type is not generic within material-ui@next

After installing material ui@next, I encountered an error in the node modules. ERROR in [at-loader] ./node_modules/material-ui/Avatar/Avatar.d.ts:8:15 11:31:52 web.1 | TS2315: Type 'ReactType' is not generic. 11:31:52 web.1 | ERROR in ...

Unlimited rotation - using setInterval function

I am encountering an issue with removing the move class from my code. Can someone please check it out for me? let lis = document.querySelectorAll('li') let arr = []; for (let i = 0; i < lis.length; i++) { arr.push(lis[i]); } setInterval( ...

Is it possible to vary the font size for different fonts within a single page?

Imagine using Helvetica for English text and a unique, exotic font (from an ASCII perspective) for another language on the same page. Even with the same font size, one font may appear larger to the eye. Is it possible to specify different font sizes for ...

Unable to set the height for ul/div elements

I'm struggling to make my navbar appear when I click the "menu button". The div seems to be present in the code, but with a height of 0. Here's the relevant section of the code causing the issue. Any suggestions on how I can resolve this? var ...

Angular 5 in conjunction with Keycloak enabling access for non-authenticated users

I have a situation where I need to implement anonymous user access in my app, and for that purpose, I am incorporating the 'keycloak-angular' library along with Angular 5. The documentation instructs me to initialize the application as shown belo ...

Tips on how to navigate back to the parent function context from a child function

I am looking for the return value to impact the parent function, like so: const blockLetters = lastD => { if(lastD != undefined && isNaN(Number.parseInt(lastD))){ return; } } const handleCVC = e => { e.preventDefault() ...

Populate a ReactJS map with JSON objects obtained from a request response within a for loop

I've been working on a React dashboard and came across a helpful library that allows me to create a line chart using a JSON object. My current objective is to retrieve 7 objects from GET requests within a for loop and populate the data map with them. ...

Show the results of fs.readdirSync() within an HTML file on the frontend

As someone who is just starting out with node.js, I've been searching online for a solution to the issue I've described in my question title. The project I'm working on involves creating a basic web API that allows users to upload their fil ...

Is there a way to abruptly terminate a node thread from my frontend application?

My React web application is designed to generate solutions for Rubik's cubes. Whenever a user inputs a query on my site, it triggers a computation process that can take anywhere from 1 second to 240 seconds. Each time a solution is found, the state is ...

"Is there a way to load JSON data into a JIT spacetree using an ActionResult in MVC

I am in the process of creating a customized JIT spacetree similar to the one showcased at this link: My goal is to generate dynamic Json data for the spacetree based on information retrieved from a database table within an MVC framework. Currently, I ha ...

Does Jackson serialize fields in uppercase letters?

When serializing my object, it appears as {name="nyname" ....}, but I need all keys to start with uppercase. For example, {Name="myname",.....}. Is there a way to achieve this using Jackson? ...

Which is the better option: replacing content with Ajax loading or appending content?

Currently, I am working on developing a predominantly ajax-driven website where content is fetched based on hashTag changes. However, I am facing a dilemma between two options: Option 1 In this option, the content is replaced with each request. Option 2 ...

Bold Chutzpah: Delving into AngularJS Testing using Jasmine and TypeScript

Currently, I am utilizing Angular 1.4.9 in combination with Jasmine 2.2.0 and Chutzpah 4.2.0. My Angular code and unit tests are both written in TypeScript within Visual Studio 2015 Update 1. The issue I am facing mirrors that which was previously discuss ...

Bidirectional linking using URL query parameters and form inputs (select boxes and sliders)

Presently, I am able to retrieve the GET parameters using $location.$$search. Nevertheless, I am still unsure about how to implement 2-way binding for both the URL and FORM in the following scenario. In the demo image below, when a user updates the FORM ...

Is it possible to have two packets within a single data object when using the onData event in NodeJS

I am facing a challenge in sending data from my server to the client using TCP and formatting it in JSON. I am currently utilizing the net module for this task. The issue arises when my socket object triggers the "on data" event, as I need to convert the b ...

Laravel Inertia Vue: Dealing with session flash message errors

I'm currently immersed in a Laravel Inertia project with a Jetstream starter pack that integrates with vue3. One of the tasks at hand is customizing the login method to check for user status. If a user is inactive, they should receive an error message ...