编辑:我在用角度做一个调查。在本项目中,将动态添加问题,并给出问题的答案模型。例如,“多重选择、纯文本、星级”
由于问题的数量和答复的数量是动态的,我也会动态地给出“输入名称”。发布表单时创建的对象如下所示。
我有这样一个对象。
{
"title": "anket başlığı",
"sms": "sms mesajı",
"question-1": "bu birinci soru",
"answer-1": "1",
"question-2": "bu ikinci soru",
"answer-2": "6",
"answers-2-1": "cevap 1",
"answers-2-2": "cevap 2",
"answers-2-4": "cevap 4",
"question-4": "soru 4",
"answer-4": "7",
"answers-4-5": "qwe1",
"answers-4-6": "qwe2",
"answers-4-7": "qwe3",
"question-5": "soru 5",
"answer-5": "6",
"answers-5-10": "ccc3",
"answers-5-11": "ccc4"
}在这个对象中,“问题-1”是第一个问题,“回答-1”是第一个问题的回答类型。“问题-2”是第二个问题,“回答-2”是第二个问题的回答类型,“回答-1,答案-2-2,答案-2-4”是第二个问题的回答。
我想在这个物体上做“问题-1,问题-2,问题-4,问题-5”的动态形状。
编辑:为了发送web服务,我需要将这个对象带到以下结构中。
{
"title": "anket başlığı",
"sms": "sms mesajı",
"questions" : [
{
"question": "bu birinci soru",
"answer_model_id": "1",
"answers": []
},
{
"question": "bu ikinci soru",
"answer_model_id": "6",
"answers": [
{
"answers": "cevap 1"
},
{
"answers": "cevap 2"
},
{
"answers": "cevap 4"
}
]
},
{
"question": "soru 4",
"answer_model_id": "7",
"answers": [
{
"answers": "qwe1"
},
{
"answers": "qwe2"
},
{
"answers": "qwe3"
}
]
},
{
"question": "soru 5",
"answer_model_id": "6",
"answers": [
{
"answers": "ccc3"
},
{
"answers": "ccc4"
}
]
}
]
}编辑2:我用变量保留问题的数量。我知道我需要用这个变量设置一个循环来完成这个任务。但“问题-第一,问题-2,4-问题,问题-5”我不知道如何区分。
发布于 2018-04-29 20:18:06
您可以使用对象作为对具有相同索引的问题的引用。对于给定密钥的分配,您可以拆分密钥并通过检查键分配值。
var data = { "title": "anket başlığı", "sms": "sms mesajı", "question-1": "bu birinci soru", "answer-1": "1", "question-2": "bu ikinci soru", "answer-2": "6", "answers-2-1": "cevap 1", "answers-2-2": "cevap 2", "answers-2-4": "cevap 4", "question-4": "soru 4", "answer-4": "7", "answers-4-5": "qwe1", "answers-4-6": "qwe2", "answers-4-7": "qwe3", "question-5": "soru 5", "answer-5": "6", "answers-5-10": "ccc3", "answers-5-11": "ccc4" },
reference = {};
data.questions = [];
Object.keys(data).forEach(k => {
var [key, index] = k.split('-');
if (!index) {
return;
}
if (!reference[index]) {
data.questions.push(reference[index] = {});
}
if (key === 'question') {
reference[index].question = data[k];
}
if (key === 'answer') {
reference[index].answer_model_id = data[k];
}
if (key === 'answers') {
reference[index].answers = reference[index].answers || [];
reference[index].answers.push({ answers: data[k] });
}
delete data[k];
});
console.log(data);.as-console-wrapper { max-height: 100% !important; top: 0; }
https://stackoverflow.com/questions/50090622
复制相似问题