1

I am here today with a question to do with key value pair arrays.

my html is as follows

<input type="checkbox" class="data" id="task_checked" value="1" email="[email protected]">
<input type="checkbox" class="data" id="task_checked" value="2" email="[email protected]">

I would like to store the following data as an array like below:

"1" => "[email protected]"
"2" => "[email protected]"

My Javascript currently is as follows:

var newTasksArr = new Array();

$("#task_checked:checked").each(function() {
    var email = $(this).attr("email");
    var id = $(this).val();
    newTasksArr['id'] = email;

});

Perhaps I am using the Jquery .each() wrong, could someone shed some light in to my question please?

Thank you for you reading. Regards.

3 Answers 3

3

Two issues :

In Javascript, an Array may only have sequential, numeric keys. If you want to use strings as keys, you want an Object.

If you want to insert an element with a key equal to the value of id, then you want newTasksArr[id] = email; without the quotes.

Sign up to request clarification or add additional context in comments.

Comments

1

You're almost right, you just need to remove the quotes around 'id' so that it uses the value the id variable contains, instead of the literal string 'id'.

You should also use an object ({}) instead of an array ([]).

var newTasks = {};
$("#task_checked:checked").each(function() {
    var email = $(this).attr("email");
    var id = $(this).val();
    newTasks[id] = email;
});

2 Comments

@PeterOlson: note that the values of "id" will be sequential integers, though. Your suggested change to an object may have consequences that are unexpected to BaconJuice. Compare: var a=[],b={}; a['0'] = 'x'; a['1'] = 'x'; b['0'] = 'x'; b['1'] = 'x'; alert(a.length); alert(b.length);
@DavidHedlund He seemed to be fairly specifically asking for key-value storage, but it looks like he might be coming from PHP, which conflates arrays and key-value dictionaries even more than JavaScript does.
0

Avoid duplicating Ids in your markup. The following should help, however you might want to tweek the jquery selector to include a context.

var arr = {};

$('input:checked').each(function() {
    var $t = $(this);

    var email = $t.attr("email");
    if (!email) {
        // you may wish to do something if email is missing
    }

    var id = $t.val();
    if (!id) {
        // deal with the error
    }

    arr[id] = email;
});

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.