2

Using jQuery, I would like to get each attribute value, insert it into an array and then insert each array into an array.

From this HTML:

   <ul>
        <li data-bbox="-121,20,-36,30">Item 1</li>
        <li data-bbox="-122,30,-46,40">Item 2</li>
        <li data-bbox="-123,40,-56,50">Item 3</li>
    </ul>

I'm trying to create this type of nested array:

var bboxArray = [
    [-121,20,-36,30],
    [-122,30,-46,40],
    [-123,40,-56,50]
];

...and convert the strings to numbers.

I'm assuming I need to do something like this:

var bboxArray = [];
$('li[data-bbox]').each(function() {
  bboxArray.push($(this).attr('data-bbox').split(','));
});
3

2 Answers 2

2

Working Example

While your code does work, it is returning strings instead of the numbers you have in your required output this will do that:

I simply added .map(Number) at the end of your push

$('li[data-bbox]').each(function() {
  bboxArray.push($(this).attr('data-bbox').split(',').map(Number));
});
Sign up to request clarification or add additional context in comments.

3 Comments

Yep. Sorry. I didn't make that more clear. I also wanted to convert from string to numbers. Thanks!
youre welcome! can you edit the title in case anyone else see it? Thanks!
I edited the title and the post to make it more clear. If you would like to suggest something additional, please let me know.
0

You can use the .map() method like so:

var bboxArray = $('ul > li').map(function() {
    return [ $(this).data('bbox').split(',') ];
}).get();

var bboxArray = $('ul > li').map(function() {
    return [ $(this).data('bbox').split(',') ];
}).get();
console.log( bboxArray );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
   <ul>
        <li data-bbox="-121,20,-36,30">Item 1</li>
        <li data-bbox="-122,30,-46,40">Item 2</li>
        <li data-bbox="-123,40,-56,50">Item 3</li>
    </ul>

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.