How would i go about getting the name of an object that's inside of an array without directly referencing the object?
This was my initial solution, but I discovered that Object.keys
does not work with an array index.
let myArrayForObjects = [];
function firstFunc(){
myArrayForObjects.push(object1, object2, object3);
}
function secondFunc(){
for (let i = 0; i < myArrayForObjects.length; i++){
let varName = Object.keys({myArrayForObjects[i]}[0]);
console.log(varName);
}
}
I posted it as here and was suggested the following solution:
let myArrayForObjects = [];
function firstFunc(){
myArrayForObjects.push(object1, object2, object3);
}
function secondFunc(){
for (let i = 0; i < myArrayForObjects.length开发者_运维问答; i++){
// Find the object in the array
let objectIndex = myArrayForObjects.indexOf(myArrayForObjects[i]);
// Get the object's name
let objectName = Object.keys(myArrayForObjects)[objectIndex];
console.log(objectName);
}
}
But that logs 1
, 2
and 3
to the console. And what I want it to log is object1
, oject2
, and object3
.
Is it even possible to do what I want? Or should I just add a property to the object with its name?
Instead of storing the objects in an array, put them in an object like so:
const myObjects = { object1, object2, object3 }
You can now either access them by name:
console.log(myObjects.object1)
Or iterate on the objects if needed:
console.log(Object.values(myObjects))
精彩评论