Реструктуризация существующего JSON на основе категории в React Native

У меня есть ответ в формате 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. Может ли кто-нибудь сказать мне, что это должен быть лучший способ решить эту проблему?

Может ли категория иметь несколько состояний?

Andrew 15.01.2019 12:18

Нет, только одно государство разрешено для определенной категории.

Francis F 15.01.2019 12:54
0
2
129
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Итак, если мы возьмем массив questionList из предоставленного вами json, мы сможем сделать следующее.

  1. Прокрутите каждый вопрос в массиве questionList.
  2. Преобразуйте вопрос в новый формат.
  3. Проверьте, встречались ли мы с этой категорией раньше.
    • Если нет, мы создадим категорию, добавим в нее новый вопрос и добавим категорию в наш массив результатов.
    • Если мы нашли категорию раньше, мы найдем ее в массиве результатов и добавим в нее новый вопрос.

Вот код

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

Спасибо, хорошо сработало :). Просто чтобы вы знали, что в вашем коде есть орфографическая ошибка для результата имени переменной, вы можете отредактировать, если хотите;)

Francis F 15.01.2019 18:36

Другие вопросы по теме