如何在本机中使用for循环遍历数组?

时间:2019-01-02 12:42:36

标签: javascript json react-native for-loop

我正在尝试在react native中循环遍历json数据。我想创建一个具有不同keyvalues的新数组,这将是循环的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 :(得分:1)

这是您想要的完整示例代码,尝试在最终循环中更改数据,您将获得所需的输出:

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

答案 1 :(得分:1)

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},
]

如果resp是具有长度和0、1、2,...键的对象,请使用Array.from(obj)将其转换为对象

如果resp已排序(每个单位都属于上一部分)

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/, '')
}

/ symbols /称为正则表达式

  • 该字符串以(第一个^符号)开头的任何字符都应包含
  • 空白(whitespace = \ s,[^ something]表示不是某物)
  • 加号表示最后一部分可以重复1次或多次

到目前为止,它找到了第一个单词

  • \ s的意思是替换单词后的空格

答案 2 :(得分:1)

使用reduce函数和一个变量来跟踪累加器数组的索引

检查类型是否为节,然后在累加器数组中推入值,并将变量值更新为1。

如果类型为单位,则将值添加到currIndex变量定义的索引处的内容中

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)

答案 3 :(得分:0)

这是一种可能的解决方案。如果我正确理解了该问题,则需要重新格式化并将该部分作为标题并将单元作为内容组合...

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"
  }
]