I have recently created an array using .map in jQuery and now I need to access elements within it. To handle this I simply iterated over the array and tried to grab the various items but I can't seem to get it to work.
$('#go').on('click', function () {
var arr = $('.plotrow').map(function () {
var o = {};
o[this.id] = [
{ lat: $(this).find('.lat input').val() },
{ long: $(this).find('.long input').val() }
]
return o;
}).get();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="coords">
<div id="plot1" class="plotrow">
<h3>Plot 1</h3>
<div class="lat">
<input type="text" id="plot1_lat" value="59.545205" class="k-textbox" />
</div>
<div class="long">
<input type="text" id="plot1_long" value="1.53572" class="k-textbox" />
</div>
</div>
<div id="plot2" class="plotrow">
<h3>Plot 2</h3>
<div class="lat">
<input type="text" id="plot2_lat" value="59.21344" class="k-textbox" />
</div>
<div class="long">
<input type="text" id="plot2_long" value="1.33437" class="k-textbox" />
</div>
</div>
<div class="plot output">
<h3>Output</h3>
</div>
<button type="button" id="go">Go!</button>
</div>
What I want to do it output the id the lat and the long from my array. No matter what I try I seem to get an undefined error. For example, I wrote the following code:
for (i = 0; i < arr.length; i++) {
console.log(arr[i]['plot1'][0]['lat']);
}
This code returned the lat for me but also an error of:
TypeError: arr[i].plot1 is undefined[Learn More]
I've tried a couple of variations but nothing seems to work. Can anyone offer a good way to access my elements?