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
-
1Man, you are doing some crazy stuff within those few code lines! :)John Doe– John Doe2013年01月13日 07:51:04 +00:00Commented Jan 13, 2013 at 7:51
-
4@JohnDoe There is a always a way to complicate things :)Patrioticcow– Patrioticcow2013年01月13日 07:55:03 +00:00Commented Jan 13, 2013 at 7:55
1 Answer 1
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
2 Comments
Explore related questions
See similar questions with these tags.