theplau
theplau

Reputation: 980

Displaying keys and values of an object with jQuery

I am trying to display the keys and values of an object but I'm getting only an error saying:

0[object Object]1[object Object]2[object Object]3[object Object]

What am I doing wrong?

My object, according to console.log is:

(4) [{…}, {…}, {…}, {…}]
0
:
{text: "Now", time: "Now"}
1
:
{text: "09:00", time: "09:00"}
2
:
{text: "09:30", time: "09:30"}
3
:
{text: "10:00", time: "10:00"}
length
:
4
__proto__
:
Array(0)

I am trying t display it with:

var html='';
$.each( data.times, function( key, val ) { 
      html+=key+val;
});
createElement("times", html );

Upvotes: 0

Views: 73

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337610

Your issue is because data.times is an array of objects, which you are attempting to loop through as if it was an array of strings.

To fix this you need to instead loop through the properties of the object within the array, which you can achieve by using Object.keys, something like this:

var data = {
  times: [{
    "09:00": "09:00",
    "09:30": "09:30",
    "10:00": "10:00"
  }]
}

var html = '';
Object.keys(data.times[0]).forEach(function(key) {
  html += key + '-' + data.times[0][key] + ' ';
});
console.log(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Note that this will only loop over the first object in the array as that's all your data structure contains. If you want to loop through more objects you'd need to add another loop around this logic.


Post question edit update:

Now that you've amended the data structure you can just loop through the objects in the array and access their keys directly:

var data = {
  times: [
    { text: "Now", time: "Now" },
    { text: "09:00", time: "09:00" },
    { text: "09:30", time: "09:30" },
    { text: "10:00", time: "10:00" }
  ]
}

var html = '';
data.times.forEach(function(obj) {
  html += obj.text + '-' + obj.time + ' ';
});
console.log(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

amit wadhwani
amit wadhwani

Reputation: 1140

Updated code.

$.each( data, function( key, val ) { 
      html+=key+val.time;
});
createElement("times", html );

Upvotes: 0

Related Questions