【问题标题】:How to loop through an array using for loop in react native?如何在本机反应中使用for循环遍历数组?
【发布时间】:2019-01-02 12:42:35
【问题描述】:

我正在尝试在本机反应中循环 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)
    })
})

【问题讨论】:

  • 将resultk定义为let resultk={}

标签: javascript json react-native for-loop


【解决方案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/这个东西叫做正则表达式

  • 字符串以(第一个 ^ 符号)除 a 以外的任何字符开始
  • 空白(空白=\s,[^something] 表示不是某事)
  • 加号表示最后一部分可以重复 1 次或多次

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

  • \s 表示也替换单词后的空格

【讨论】:

  • 如何列出内容数组?。我想在上面映射
  • 如果它不是一个数组,而是像这样: { 0: object, 1: object, 2: object, length: 3, } 使用Array.from(arrayLike) 将其转换为数组如果那是什么你问或者如果你问我如何访问结果,它是 result 数组,在我的脚本之后使用它
【解决方案2】:

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

检查它的类型是section,然后在累加器数组中推送值并将变量值更新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】:

这是你想要的完整示例代码,尝试使用最终循环更改数据,你会得到你想要的输出:

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

【讨论】:

    【解决方案4】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多