Home > Blockchain >  How would I get the name of an object from a for loop?
How would I get the name of an object from a for loop?

Time:09-21

So, I'm trying to figure out how I can return the name of an object from a for loop. It seems that whenever you push an object into an array, the name seemingly vanishes, and whenever I run a for loop, I can never get the name to show. For example:

/* I know this is a variable, but I'm asking about this for something like a fetch, where the returned json is a list of objects. test is just an example name for those objects returned from the fetch. */
let test = {
    hi: 'hi'
};
let arr = [];
arr.push(test);
/* Here, I wish for the name of the objects, like if from a fetch we have an object test: {hi: 'hi'} from a fetch, and I put that into a for  loop, I want to be able to extract the name of that object and use it, instead of the only things being accessible are the object entries */
for (let count in arr) {
    console.log(arr[count])
};

Here, the name of the object will suddenly vanish, and there's no getter inside the object to return the name. In this example, my goal would be for 'test' to be returned. Without having a getter inside the object for the name How can I get some sort of list of objects, and put those objects in a for let loop that will actually return the name of the objects inside the loop--if there even is a way?

CodePudding user response:

If you want to store a name/value list, use an object

let obj = {"test": {hi: "hi"}}; 
Object.entries(obj).forEach(([key, value]) => 
  console.log(`${key} = ${JSON.stringify(value)}`)
);

CodePudding user response:

Print out your count variable. It is what you are looking for.

It should better bet named key instead

CodePudding user response:

The test is a variable name that only holds the referance of the object in the memory, but it's not the name of the object, if you need to have each object have its own name, I suggest you add name property in the object.

let test = {
    hi: 'hi',
    name: 'test',
};
let arr = [];
arr.push(test);
for (let count in arr) {
    console.log(arr[count].name);
};

  • Related