How is it possible to access the values inside an array? i have already checked the jQuery documentation but my scenario isn't listed.
Array Structure:
var myData = [{
label: "erster",
id: 0,
Name: "Ein Name"
}, {
label: "zweiter",
id: 1,
Name: "Der zweite Name"
}, {
label: "dritter",
id: 2,
Name: "Dritter Name"
}];
And here is my try to show up some results in the browser:
$(document).ready(function() {
$.each(myData, function (i, val) {
alert(i + " " + val);
});
});
The Response is no value just Object,Object
. I think I understand the structure of $.each
a little bit (thanks to the documentation) but I see no way to go inside one of this array's elements.
Thanks for any help.
EDIT:
#Ok thanks a lot for those very good and clear inputs. Now i understand how to access the values. Can someone offer me a trick how to create an HTML Output for those Elements?
Result should be something like:
<div id="accordion">
<h3>'val.labelfromelement1'</h3>
<div class="notimportant">'val.Namefromelement1'</div>
<h3>'val.labelfromelement2'</h3>
<div class="notimportant">'val.Namefromelement2'</div>
<h3>'val.labelfromelement3'</h3>
<div class="notimportant">'val.Namefromelement3'</div>
<h3>'val.labelfromelement4'</h3>
<div class="notimportant">'val.Namefromelement4'</div>
</div>
as you can see, it should result in an accordion that will be automatic increase if a we create a new element in the array (The Array is from a chart)
With the following Code it shows me just the last instance / Part / Segment / what ever :-)
var myData = [
{
label: "erster",
id: 0,
Name:"Ein Name"
},
{
label: "zweiter",
id: 1,
Name:"Der zweite Name"
},
{
label: "dritter",
id: 2,
Name:"Dritter Name"
}
]
$(document).ready(function(e) {
$.each(myData, function (i, val) {
myAccordion = "<h3>" + val.label + "</h3><div>" + val.Name + "</div>";
});
$("#myAccordionDiv").html(myAccordion);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
<div id="myAccordionDiv">
</div>
</body>
deep breathing :-) what can i do now?
Your $.each
code is fine, the issue is because you're trying to append a string to an object results in type coercion to a string, hence the objects in the array are converted to [Object object]
.
Firstly, don't append the object as a string, and secondly use the console for debugging instead (To see the console, it's normally F12 in your browser).
$(document).ready(function() {
$.each(myData, function (i, val) {
console.log(i, val);
});
});
Note that to get the properties of each object within the array, you can access them from the val
parameter in your each()
loop:
$.each(myData, function (i, val) {
console.log(val.label);
console.log(val.id);
console.log(val.Name);
});
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments