[英]How would i go about getting a specific object based on the value of a string with javascript?
[英]How would i go about getting the name of an object that's inside of an array without directly referencing the object?
這是我最初的解決方案,但我發現Object.keys
不適用於數組索引。
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);
}
}
我將其發布為此處,並建議采用以下解決方案:
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);
}
}
但這會將1
、 2
和3
記錄到控制台。 我希望它記錄的是object1
、 oject2
和object3
。
甚至可以做我想做的事嗎? 或者我應該只用它的名字向 object 添加一個屬性嗎?
不要將對象存儲在數組中,而是將它們放在 object 中,如下所示:
const myObjects = { object1, object2, object3 }
您現在可以通過名稱訪問它們:
console.log(myObjects.object1)
或者根據需要迭代對象:
console.log(Object.values(myObjects))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.