Как перебрать массив, используя для цикла в реагировать родной? - PullRequest
0 голосов
/ 02 января 2019

Я пытаюсь перебрать json-данные в реагировать на натив. Я хочу создать новый массив с другими key, и values будет зацикленным результатом json. Я пробовал следующее, но ничего не работает, так какожидается. Формат ответа json будет следующим.

json

 0: {key: 0, id: 0, type: "section", title: "A1. India's Economic Development", duration: 0, …}
    1: {key: 1, id: "1", type: "unit", title: "1. India as a Developing Economy", duration: 0, …}
    2: {key: 2, id: "2", type: "unit", title: "2. Understanding India’s economic transition", duration: 0, …}
    3: {key: 17, id: 0, type: "section", title: "A2. National Income", duration: 0, …}
    4: {key: 18, id: "5", type: "unit", title: "1. India in the global economy", duration: 0, …}
    5: {key: 19, id: "6", type: "unit", title: "2. China, India and the rise of Asia", duration: 0, …}

Я хочу такой массив

const dataArray = [
  {
    title: "India's Economic Development",
    content:
      "India as a Developing Economy",
      "Understanding India’s economic transition"

  },
  {
    title: "National Income",
    content:
      "India in the global economy",
      "China, India and the rise of Asia"
  }
]

Следующийэто цикл, который я сделал, но ничего не идет. Пожалуйста, помогите

.then((response) => response.json())
.then((responseData) => {

    responseData.map(detail => {

        let resultk = [];
        //console.log( detail.data.curriculum);
        for (var i = 0, j = 0; i < detail.data.curriculum.length; i++) {
            curr = detail.data.curriculum;
            console.log(curr.title);
            if (curr.type === "section") {
                resultk['title'] = curr.title;
                this.result[j++] = resultk;

            } else if (curr.type === "unit") {
                resultk['content'] = curr.title;
            }
        }
        console.log(resultk)
    })
})

Ответы [ 4 ]

0 голосов
/ 02 января 2019

Вот одно из возможных решений. Если я правильно понимаю вопрос, вы хотите переформатировать и объединить раздел в качестве заголовка и блок (ы) в качестве содержания ...

var data = {
    0: { key: 0, id: 0, type: "section", title: "A1. India's Economic Development", duration: 0 },
    1: { key: 1, id: "1", type: "unit", title: "1. India as a Developing Economy", duration: 0 },
    2: { key: 2, id: "2", type: "unit", title: "2. Understanding India’s economic transition", duration: 0 },
    3: { key: 17, id: 0, type: "section", title: "A2. National Income", duration: 0 },
    4: { key: 18, id: "5", type: "unit", title: "1. India in the global economy", duration: 0 },
    5: { key: 19, id: "6", type: "unit", title: "2. China, India and the rise of Asia", duration: 0 }
};

var keys = Object.keys(data);

var dataArray = [];
var push = true;
var toPush = null;

for (var i = 0; i < keys.length; i++) {

    var key = keys[i];
    var obj = data[key];

    switch (obj.type) {
        case "section":
            if (toPush !== null) {
                dataArray.push({ ...toPush });
            }
            toPush = {};
            var titleText = obj.title.split(".")[1].trim();//if there is always a "." in the title string this will clean that up;
            toPush.title ? toPush.title += `, ${titleText}` : toPush.title = titleText;
            push = true;
            break;
        case "unit":
            push = false;
            var contentText = obj.title.split(".")[1].trim();//if there is always a "." in the title string this will clean that up;
            toPush.content ? toPush.content += `, ${contentText}` : toPush.content = contentText;
            break;
        default: break;
    }
}

//push the last one
dataArray.push({ ...toPush });

console.log(JSON.stringify(dataArray, null, 2));

//result =>
[
  {
    "title": "India's Economic Development",
    "content": "India as a Developing Economy, Understanding India’s economic transition"
  },
  {
    "title": "National Income",
    "content": "India in the global economy, China, India and the rise of Asia"
  }
]
0 голосов
/ 02 января 2019
const resp = [
    {key: 0, id: 0, type: "section", title: "A1. India's Economic Development", duration: 0},
    {key: 1, id: "1", type: "unit", title: "1. India as a Developing Economy", duration: 0},
    {key: 2, id: "2", type: "unit", title: "2. Understanding India’s economic transition", duration: 0},
    {key: 17, id: 0, type: "section", title: "A2. National Income", duration: 0},
    {key: 18, id: "5", type: "unit", title: "1. India in the global economy", duration: 0},
    {key: 19, id: "6", type: "unit", title: "2. China, India and the rise of Asia", duration: 0},
]

Если соответственно это объект с длиной и ключами 0, 1, 2, ..., используйте Array.from (obj) для преобразования его в объект

Если отсортировано (каждая единица принадлежит к предыдущему разделу)

const result = []
resp.forEach(item => {
    if (item.type === 'section') { // create a new collection
        result.push({
            title: item.title,
            content: []
        })
    } else if (item.type === 'unit') {
        if (result.length === 0) throw new Error('No section specified yet')
        result[result.length - 1].content.push(item.title)
    } else {
        throw new TypeError('Invalid data type')
    }
})

Чтобы обрезать первое слово из заголовка, используйте

function removeFirstWord(str) {
    return str.replace(/^[^\s]+\s/, '')
}

Символ / / называется регулярным выражением

  • Строка начинается с (первого знака ^) любого символа, ожидающего
  • пробел (пробел = \ s, [^ что-то] означает не что-то)
  • знак плюс означает, что последняя часть может повторяться 1 или более раз

пока он находит первое слово

  • означает \ s также заменить пробел после слова
0 голосов
/ 02 января 2019

Используйте функцию reduce и переменную для отслеживания индекса массива аккумулятора.

Проверьте, что это тип раздела, затем в массиве аккумулятора нажмите значение и обновите значение переменной на 1.

Если тип является единицей, добавьте значение в контенте, индекс которого определяется как currIndex variable

let value = [{
    key: 0,
    id: 0,
    type: "section",
    title: "A1. India's Economic Development",
    duration: 0
  },
  {
    key: 1,
    id: "1",
    type: "unit",
    title: "1. India as a Developing Economy",
    duration: 0
  },
  {
    key: 2,
    id: "2",
    type: "unit",
    title: "2. Understanding India’s economic transition",
    duration: 0
  },
  {
    key: 17,
    id: 0,
    type: "section",
    title: "A2. National Income",
    duration: 0
  },
  {
    key: 18,
    id: "5",
    type: "unit",
    title: "1. India in the global economy",
    duration: 0
  },
  {
    key: 19,
    id: "6",
    type: "unit",
    title: "2. China, India and the rise of Asia",
    duration: 0
  }
]

let currIndex = -1;
let k = value.reduce((acc, curr) => {

  if (curr.type === 'section') {
    acc.push({
      title: curr.title.split('.')[1].trim(),
      content: []
    })
    currIndex += 1
  } else {
    acc[currIndex].content.push(curr.title)
  }

  return acc;


}, []);
console.log(k)
0 голосов
/ 02 января 2019

Вот полный пример кода того, что вы хотите, попробуйте изменить данные с помощью последнего цикла, и вы получите желаемый результат:

testingggg = () => {
    var data = {
        0: {key: 0, id: 0, type: "section", title: "A1. India's Economic Development", duration: 0},
        1: {key: 1, id: "1", type: "unit", title: "1. India as a Developing Economy", duration: 0},
        2: {key: 2, id: "2", type: "unit", title: "2. Understanding India’s economic transition", duration: 0},
        3: {key: 17, id: 0, type: "section", title: "A2. National Income", duration: 0},
        4: {key: 18, id: "5", type: "unit", title: "1. India in the global economy", duration: 0},
        5: {key: 19, id: "6", type: "unit", title: "2. China, India and the rise of Asia", duration: 0}
    }

    var keys = [];
    for(var k in data) keys.push(k);

    //alert("total " + keys.length + " keys: " + keys);

    var dataArray = [] 

    for(i=0;i<keys.length;i++)
    {
        var newObj = { // Change your required detail here
            type: data[i].type,
            title: data[i].title
        }
        dataArray.push(newObj);
    }
    console.log(dataArray);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...