I have an array incoming from Express to a Jade template that looks like this:
[{ id: 11,
firstname: 'asdfasdf',
lastname: 'asdfasdf',
},
{ id: 12,
firstname: 'asdfadf',
lastname: 'asdfasdf',
}]
I want to grab one of these elements and display it along with its properties on the page. I have read several other answers here but none seem to answer my question/work properly.
I have tried,
#{data[0].id}
!{data[0].id}
#{data.id[0]}
data.id[0]
data[0].id
...and countless other combinations, how can i print this out properly? I know my data object is being passed in correctly because I can iterate through it using a for loop elsewhere in my page. But if I only want to grab ONE element ONLY from the array, how can i achieve this?
Is this even possible without looping through the entire json array object?
UPDATE: my problem was due to the array structure being different than what I initially thought it was. My mistake, the correct way to access elements is using
#{data[0].id}
This is an array of JSON objects so you need to iterate it through
var newObject = [{ id: 11,
firstname: 'asdfasdf',
lastname: 'asdfasdf',
},
{ id: 12,
firstname: 'asdfadf',
lastname: 'asdfasdf',
}];
for (var i = 0; i < newObject.length; i++) {
var object = newObject[i];
for (var property in object) {
alert('item ' + i + ': ' + property + '=' + object[property]);
}
}
or
var newObject = "[{ id: 11,firstname: 'asdfasdf',lastname: 'asdfasdf',},{ id: 12, firstname: 'asdfadf', lastname: 'asdfasdf',}]";
var obj = eval(newObject);
alert(obj[0].id);