-2

I have an array with objects inside of it.

var obj1 = [
 user1 = {
  "name" : "John",
  "age" : 24,
  "city" : "London"
 },
 user2 = {
  "name" : "Jane",
  "age" : 22,
  "city" : "New York",
 }
];

Now what I would like to do is to get name of the objects inside the array so in this case it would be "user1" and "user2".

FIRST TRY

At first I tried doing it like this:

for(i = 0; i < obj1.length; i++){
 document.getElementById('app').innerHTML += obj1[i];
}

And the outcome is [object Object][object Object]

SECOND TRY

So then I tried to use JSON.strigify on the objects, but then it returns the whole object and not it's name as I would like to:

for(i = 0; i < obj1.length; i++){
 document.getElementById('app').innerHTML += JSON.stringify(obj1[i]);
}

Outcome:

{"name":"John","age":24,"city":"London"}{"name":"Jane","age":22,"city":"New York"}

QUESTION

Is it possible, and if yes how should I go about displaying names of all of the objects inside of an array, but not displaying their content. Desired outcome:

user1 user2
aMJay
  • 2,215
  • 6
  • 22
  • 34

1 Answers1

1

This is what your code does:

  1. Create an object
  2. Implicitly create a global variable called user1 and assign that object to it
  3. Create another object
  4. Implicitly create a global variable called user2 and assign that object to it
  5. Create an array
  6. Populate the array with the values of the variables user1 and user2
  7. Create a local variable called obj1 and assign the array to it

The array knows nothing about the variables user1 and user2. They were just the source of the data copied into it.

The objects know nothing about the variables user1 and user2. Relationships in JavaScript are unidirectional. A variable can refer to an object (in fact, multiple variables can refer to the same object) but there is no way to backtrack.

Now what I would like to do is to get name of the objects inside the array so in this case it would be "user1" and "user2".

You can't.

(Well, not without doing horrible guesswork like looping over every global variable (property of the window object, browser JS only) and comparing it to the object … and if you are going down that route then you need to redesign your code to achieve your real goal in a more sensible way).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • So let me clarify if I'm getting your answer right. The problem was with my flawed perception of how arrays of objects should be created. The "user1" and "user2" are variables which are completly redundant in this case because I cannot access their names the way i wanted? – aMJay Mar 12 '18 at 10:30
  • @MateuszJuruś — Yes. – Quentin Mar 12 '18 at 10:31