0

I'm building an array of objects in JS, this is my structure:

$("li.user_task").each(function() {
    tasks.push({
        taskid: $(this).data("taskid"),
        productid: $(this).data("product-id"),
        productposition: $(this).data("product-position")
    });
});

This is working nicely, my output on console.log():

[Object, Object, Object, Object]
0: Object
productid: 2
productposition: 1
taskid: 150
__proto__: Object
1: Object
productid: 1
productposition: 1
taskid: 151
__proto__: Object
2: Object
productid: 2
productposition: 2
taskid: 155
__proto__: Object
3: Object
productid: 1
productposition: 3
taskid: 157
__proto__: Object
length: 4
__proto__: Array[0]

I don't want my keys starting from 0 though, in this very example I'd actually like the field "taskid" to be the key for the object, how could I achieve this?

3
  • 2
    these are array indexes starting from zero, not your keys. Commented Sep 24, 2013 at 10:14
  • 1
    If you use custom Keys in an Array e.g. 2 the key 0 and 1 gets an undefined and the array has a length of 3 (thats not a got practice) Commented Sep 24, 2013 at 10:15
  • Looks like you are talking about index. Not key. Commented Sep 24, 2013 at 10:23

1 Answer 1

1

this should work

 $("li.user_task").each(function() {
  tasks[$(this).data("taskid")]=({
     taskid: $(this).data("taskid"),
     productid: $(this).data("product-id"),
     productposition: $(this).data("product-position")
 });
});

unless, your taskid is not unique.

and yes as @Bernhard mentioned... with integers as key of an array.. the length of an array differs....

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

1 Comment

Thats not good... try this: var test = []; test[150] = {}; console.log(test); Then you know whats the problem with that

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.