Home > Software engineering >  How can I get the name of an object that's inside of an array without directly referencing the
How can I get the name of an object that's inside of an array without directly referencing the

Time:12-06

I have some objects inside an array and a function that i would like to return the name of the object.

let myArrayForObjects = [];

function firstFunc(){
    myArrayForObjects.push(object1, object2, object3);

}

function secondFunc(){
    for (let i = 0; i < myArrayForObjects.length; i  ){
        let varName = Object.keys({myArrayForObjects}[0]); 
        console.log(varName);
    }
}

So basically i want it to print object1, object2 and object3. My issue seems to be that the Object.keys trick does not seem to work with an array entry. So i am looking for other ways to tackle this.

CodePudding user response:

To get the name of an object that is inside of an array without directly referencing the object, you can use the Object.keys() method and the indexOf() method to find the object in the array, and then retrieve its name.

e.g:

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);
    }
}

CodePudding user response:

The Object.keys method returns an array of the property names of an object, so it will not work as you expect when applied to an array entry. Instead, you can use the typeof operator to check the type of the value in each entry of the array, and then use the Object.keys method if the value is an object.

Here is an example of how you could implement this:

function secondFunc() {
  for (let i = 0; i < myArrayForObjects.length; i  ) {
    if (typeof myArrayForObjects[i] === 'object') {
      let varName = Object.keys(myArrayForObjects[i]);
      console.log(varName);
    }
  }
}

This code uses the typeof operator to check the type of the value in each entry of the myArrayForObjects array. If the value is an object, the code uses the Object.keys method to get the property names of the object and then logs them to the console.

  • Related