0

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

2
  • 1
    Man, you are doing some crazy stuff within those few code lines! :) Commented Jan 13, 2013 at 7:51
  • 4
    @JohnDoe There is a always a way to complicate things :) Commented Jan 13, 2013 at 7:55

1 Answer 1

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

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

2 Comments

i edited. i meant those to be objects as well... but i guess i can always convert your array back into object
Javascript objects are key value pairs, there is not much sense in code like {1: {{area: "high"},{area: "high"}}} , however, arrays make more sense and you can use {1: [{area: "high"},{area: "high"}}], this would be an object with a property called "1" that contains array of objects, each having an area property

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.