从另一个JSON对象创建JSON对象

create JSON object from another JSON object

本文关键字:对象 JSON 创建 另一个      更新时间:2023-09-26

我不知道标题是否适合我想做的事情。

我有以下对象数组

    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] });
}

如果这不是你想要的,那么也许你应该使用有效的语法来更好地解释它。

以下是您所问问题的答案:

var object1 = JSON.parse(jsonString1);
// Do something to object1 here.
var jsonString2 = JSON.stringify(object1);