У меня есть ответ в формате JSON, который я получаю от сервера, как показано ниже.
{
"questionList": [{
"qno": "1",
"state_name": "State1",
"category_name": "Category1",
"question_type": "type1",
"question": "This is question 11",
"options": ["No", "yes "]
},
{
"qno": "2",
"state_name": "State1",
"category_name": "Category1",
"question_type": "type1",
"question": "This is question12",
"options": ["No", "yes "]
},
{
"qno": "3",
"state_name": "State1",
"category_name": "Category2",
"question_type": "type2",
"question": "This is question 21",
"options": ["No ", "yes "]
},
{
"qno": "4",
"state_name": "State1",
"category_name": "Category3",
"question_type": "type1",
"question": "This is question 31",
"options": ["No ", "yes "]
},
{
"qno": "5",
"state_name": "State1",
"category_name": "Category3",
"question_type": "type1",
"question": "This is question 32",
"options": ["No ", "yes "]
}
]
}
Теперь я хочу реструктурировать его на основе категорий, чтобы вопросы с несколькими одинаковыми категориями попадали в одну категорию, а также в несколько моих собственных переменных. Ниже приведен пример того, как это должно выглядеть.
[
{
"state": "State1",
"category": "Category1",
"questions": [
{
"questionID": "1",
"question": "This is question 11",
"options": ["No ", "yes "],
"status": 0,
"files": [],
"questionType": "type1"
},
{
"questionID": "2",
"question": "This is question12",
"options": ["No ", "yes "],
"status": 0,
"files": [],
"questionType": "type1"
}
]
},
{
"state": "State1",
"category": "Category2",
"questions": [
{
"questionID": "3",
"question": "This is question 21",
"options": ["No ", "yes "],
"status": 0,
"files": [],
"questionType": "type2"
}
]
},
{
"state": "State1",
"category": "Category3",
"questions": [
{
"questionID": "4",
"question": "This is question 31",
"options": ["No ", "yes "],
"status": 0,
"files": [],
"questionType": "type1"
},
{
"questionID": "5",
"question": "This is question 32",
"options": ["No ", "yes "],
"status": 0,
"files": [],
"questionType": "type1"
}
]
}
]
Я не особо разбираюсь в операциях с JSON. Может ли кто-нибудь сказать мне, что это должен быть лучший способ решить эту проблему?
Нет, только одно государство разрешено для определенной категории.
Итак, если мы возьмем массив questionList из предоставленного вами json, мы сможем сделать следующее.
Вот код
let data = [{qno: "1", state_name: "State1", ... }, ... ] // notice that this is the questionList array and not an object
let categories = []; // to track the categories that you have found
let result = []; // where your results will be stored
data.forEach(question => {
// create the question
let newQuestion = {};
newQuestion.questionID = question.qno;
newQuestion.question = question.question;
newQuestion.options = question.options;
newQuestion.status = 0;
newQuestion.files = [];
newQuestion.questionType = question.question_type;
// check to see if we have the category, if not create it
if (categories.indexOf(question.category_name) === -1) {
// create a new category
let newCategory = {};
newCategory.state = question.state_name;
newCategory.category = question.category_name;
newCategory.questions = [];
newCategory.questions.push(newQuestion); // add the question to the category we just created
result.push(newCategory); // add the category to the result
categories.push(question.category_name); // track the category so we know not to create a new one
} else {
// search for the category
let foundCategory = result.filter(group => group.category === question.category_name);
// if we have found a category add the new question to it
if (foundCategory.length) {
foundCategory[0].questions.push(newQuestion);
}
}
});
console.info(result);
Спасибо, хорошо сработало :). Просто чтобы вы знали, что в вашем коде есть орфографическая ошибка для результата имени переменной, вы можете отредактировать, если хотите;)
Может ли категория иметь несколько состояний?