1

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?

1
  • I think you want something like this: jsfiddle.net/ohezw3jr (look at developer console) Commented Sep 6, 2017 at 14:24

3 Answers 3

4

You're iterating over an array that looks like

[
    {
        "plot1": [
            {
                "lat": "59.545205"
            },
            {
                "long": "1.53572"
            }
        ]
    },
    {
        "plot2": [
            {
                "lat": "59.21344"
            },
            {
                "long": "1.33437"
            }
        ]
    }
]

meaning in the first iteration, you get

{"plot1": [ ... ]},

but the second iteration gets you

{"plot2": [ ... ]},

and then your arr[i]['plot1'] is undefined, as the key is plot2 etc.


It would make it easier on you if you created an object instead

$('#go').on('click', function () {
    var obj = {};

  $('.plotrow').each(function() {
    obj[this.id] = {
      lat: $(this).find('.lat input').val(),
      lon: $(this).find('.long input').val()
    };
  });
});

and you'd end up with

{
    "plot1": {
        "lat": "59.545205",
        "lon": "1.53572"
    },
    "plot2": {
        "lat": "59.21344",
        "lon": "1.33437"
    }
}

where you could just do obj.plot1.lat to access it, or to iterate do

$.each(obj, function(_,item) {
    var lat = item.lat;
    var lon = item.lon;
})
Sign up to request clarification or add additional context in comments.

2 Comments

This makes more sense @adeneo I have implemtned this approach which helps to simplify the structure. One question regarding iteration, item.lat and item.lon return as undefined. item returns as the row id.
@Yanayaya - you're right, I forgot that jQuery.fn.each has the item as the first argument, but when using just jQuery.each the item would be the second argument. They are a bit different. I've edited the answer to fix that.
2

By changing your for loop to look like this, you can get all of the values you need.

Essentially you were trying to loop over plot1 while you were in plot2.

for (i = 0; i < arr.length; i++) {
    var plot = 'plot' + (i + 1);
    console.log(arr[i][plot][0]['lat']);            
    console.log(arr[i][plot][1]['long']);            
}

Comments

1

Within you jQuery.map() would be better to return an object like this:

{
  id: this.id,
  lat: $(this).find('.lat input').val(),
  long: $(this).find('.long input').val()
}

Code:

$('#go').on('click', function () {
  var arr = $('.plotrow')
    .map(function () {
      return {
        id: this.id,
        lat: $(this).find('.lat input').val(),
        long: $(this).find('.long input').val()
      };
    })
    .get();

  // Accessing element in array
  arr.forEach(function (el) {
    console.log('Element id:', el.id);
    console.log('Element lat:', el.lat);
    console.log('Element long:', el.long);
  });
});
<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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.