我不知道这个标题是否适合我想做的事情。
我有以下对象数组
array([0]: {category: "10",
question: "101"},
[1]: {category: "10",
question: "102"},
[2]: {category: "20",
question: "201"}
);
我想将所有元素分组为如下所示:
array([0]: {category: "10", {question: "101",
question: "102"}},
category: "20", {question: "201"}});
我不知道这是否可能,或者是否有另一种更好的方法来解决这个问题(也许使用二维数组?),但任何帮助将不胜感激。
谢谢!
抱歉,缺少信息,以下是我创建对象数组的方法:
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")
});
});
});
并获得具有以下结构的对象数组:
[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
尝试创建我的新数组:
for(var i = 0; i < jsonObj.length; i++){
temp[jsonObj[i].category] = jsonObj[i].question;
}
但我没有得到所有值:
[483: "1549", 1052: "3701", 1053: "3702"]
最佳答案
你有:
var arr = [
{category: "10", question: "101"},
{category: "10", question: "102"},
{category: "20", question: "201"}
];
你想要(我想):
var arrRequired = [
{category: "10", question : ["101", "102"] },
{category: "20", question : ["201"] }
];
我会给你:
var obj = {
"10" : ["101", "102"],
"20" : ["201"]
};
要将你所拥有的转化为我能给你的,你可以这样做:
var result = {};
arr.forEach(function(item) {
if (!result[item.category])
result[item.category] = [item.question];
else
result[item.category].push(item.question);
});
要从我给你的东西中得到你想要的东西,你可以这样做:
var arrRequired = [];
for (var category in result){
arrRequired.push({ 'category' : category, 'question' : result[category] });
}
如果这不是您想要的,那么也许您应该使用有效的语法更好地解释它。
关于javascript - 从另一个 JSON 对象创建 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20548028/