Patrioticcow
Patrioticcow

Reputation: 27058

how to create JavaScript object using a for loop?

i have an object sample data:

[Object, Object, Object]
  0: Object
    test_id: "1"
    area: "high"
  1: Object
    test_id: "1"
    area: "saw"
  2: Object
    test_id: "2"
    area: "look"

i am trying to create a new object by grouping by test_id.

var obj = new Object();
$.each(data, function(k, v){
    obj[v.test_id] += {area: v.area};
});

this doesn't seem to work, it returns only one object line...

i am trying to get something like:

1: {
    {area: "high"}
    {area: "saw"}
}
2: {
    {area: "look""
}

any ideas? thanks

Upvotes: 0

Views: 87

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276596

After your edit I notice something, you're trying to create a javascript object with a property with no name, this is not the format. In JSON (javascript object notation) each property must have a value, what you are trying to store better fits an array.

Instead, push it into an array

    $.each(data, function(k, v){
    obj[v.test_id].area.push(v.area);
});

just remember to create obj[v.test_id] first and to set its area property to []. This results in:

1: {
    area: ["high","saw"]
}
3: {
    area: ["look"]
}

Also, if you're willing to consider using underscore it has very powerful (yet basic) collection methods, you might want to have a look at http://underscorejs.org/#groupBy

Upvotes: 1

Related Questions