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