Reputation: 217
I don't know if the title is the right one for what I want to do.
I have the following array of objects
array([0]: {category: "10",
question: "101"},
[1]: {category: "10",
question: "102"},
[2]: {category: "20",
question: "201"}
);
And I want to group all the elements into something like this:
array([0]: {category: "10", {question: "101",
question: "102"}},
category: "20", {question: "201"}});
I don't know if this is possible or if there's another better way to solve this problem (maybe with a two-dimensional array?) but any help would be very appreciated.
Thanks!
Sorry for the lack of information, here is how I create my array of objects:
var arr_sections = [];
var arr_questions = [];
var jsonObj = [];
$('.ui-sortable-nostyle').each(function(){
arr_sections.push($(this).attr("sec_id"));
});
// create json object with pairs category - question
$(".sortable2").each(function(i){
$(this).children().each(function(j){
var cat = arr_sections[i];
jsonObj.push({
category: arr_sections[i],
question: $(this).attr("ques_id")
});
});
});
And got an array of objects with the following structure:
[Object, Object, Object, Object, Object]
0: Object
category: "1052"
question: "3701"
__proto__: Object
1: Object
category: "1053"
question: "3702"
__proto__: Object
2: Object
category: "483"
question: "1550"
__proto__: Object
3: Object
category: "483"
question: "1548"
__proto__: Object
4: Object
category: "483"
question: "1549"
__proto__: Object
length: 5
Tried to create my new array:
for(var i = 0; i < jsonObj.length; i++){
temp[jsonObj[i].category] = jsonObj[i].question;
}
But I don't get all values:
[483: "1549", 1052: "3701", 1053: "3702"]
Upvotes: 0
Views: 13339
Reputation: 993
Here is the answer to what you asked:
var object1 = JSON.parse(jsonString1);
// Do something to object1 here.
var jsonString2 = JSON.stringify(object1);
Upvotes: -3
Reputation: 27823
You have:
var arr = [
{category: "10", question: "101"},
{category: "10", question: "102"},
{category: "20", question: "201"}
];
You want (i suppose):
var arrRequired = [
{category: "10", question : ["101", "102"] },
{category: "20", question : ["201"] }
];
I will give you:
var obj = {
"10" : ["101", "102"],
"20" : ["201"]
};
To convert what you have to what i will give you, you can do:
var result = {};
arr.forEach(function(item) {
if (!result[item.category])
result[item.category] = [item.question];
else
result[item.category].push(item.question);
});
To get to what you want from what i gave you, you can do:
var arrRequired = [];
for (var category in result){
arrRequired.push({ 'category' : category, 'question' : result[category] });
}
If that is not what you want, then perhaps you should explain it better, using valid syntax.
Upvotes: 5