0

I have a problem with defining array from HTML data automatically.

Here is my data:

<div id="events">
    <div id="blabla" data-title="Five K for charity" data-date="01/13/2013"></div>
    <div id="bleble" data-title="Dinner" data-date="01/25/2013"></div>
    <div id="Div1" data-title="Meeting with manager" data-date="01/01/2013"></div>
</div>

And I want to define an array like this:

var events = [
        { Title: "Five K for charity", Date: new Date("01/13/2013") },
        { Title: "Dinner", Date: new Date("01/25/2013") },
        { Title: "Meeting with manager", Date: new Date("01/01/2013") }
    ];

I can get the data from that like this:

$("#events > div").each(function (index) {
        console.log("{ Title: " + "\"" + $(this).data("title") + "\", " + "Date: new Date(\"" + $(this).data("date") + "\") }");
    });

But I dont know how to "print" them into that array. Is there a way how to do that?

I'll be glad for any answer :-)

2 Answers 2

4
var events = [];

$("#events > div").each(function (index) {
    events.push({
        Title: $(this).data("title"),
        Date: new Date($(this).data("date"))
    })
});
Sign up to request clarification or add additional context in comments.

4 Comments

Date is probably not a good name for a property key (probably not even legal?)
Since Date is no keyword it should work. Changing the name would be different from the original requirements of the question. But yes, I would also recommend using a different name for the attribute.
Oops, bikeshedder is right, I should check my sources better. Date is ok to use, but +1 to try to find another.
fyi. Date is not listed as reserved word in the MDN: developer.mozilla.org/en-US/docs/JavaScript/Reference/…
1

What you're doing at the moment is forming them as some fragile JSON format.

Instead you should be creating an object literal directly;

$("#events > div").each(function (index) {
   var obj = { 
       Title: $(this).data("title"), 
       Date: new Date($(this).data("date")) 
   };
});

And to get it in an array you could use jQuery's map():

var ar = $("#events > div").map(function (index) {
   return { 
       Title: $(this).data("title"), 
       Date: new Date($(this).data("date")) 
   };
});

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.