-3

I'm confused on how can I loop through this, to display all the names?

var x = [
           { "name":[{"value":"John"}] }, 
           { "name":[{"value":"Sam"}] },
           { "name":[{"value":"Michael"}] }
        ]

For example with the following, but how do I access the arrays?

   var a = ["a", "b", "c"];
       a.forEach(function(entry) {
       console.log(entry);
   });
userden
  • 1,615
  • 6
  • 26
  • 50
  • 1
    You can find your answer in this topic http://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object – KCarnaille Aug 31 '16 at 12:41
  • 1
    That is a **very** bizarre structure. You have an array of objects, where each object has a `name` property referring to an *array* of objects (with one object each) with a `value` property containing the actual name. `x.forEach(function(entry) { console.log(entry.name[0].value); })` But I would strongly recommend changing the structure. – T.J. Crowder Aug 31 '16 at 12:42
  • 1
    @T.J.Crowder Yes, absolutely right. A structure like `var x = [{"name":"John"}, {"name":"Sam"}, {"name":"Michael"}]` will be fairly easy to manipulate and more efficient. – Mohammad Usman Aug 31 '16 at 12:45

1 Answers1

1
var x = [
           { "name":[{"value":"John"}] }, 
           { "name":[{"value":"Sam"}] },
           { "name":[{"value":"Michael"}] }
        ];

for (var i = 0; i < x.length; i++)
    $(".output").append($("<div/>").text(x[i].name[0].value));

https://jsfiddle.net/4yhefryk/

Zay Lau
  • 1,856
  • 1
  • 10
  • 17