我试图遍历JSON数据反应native.I想创建一个不同的新的阵列key
和values
将是环形JSON result.I've试过以下,但没有什么工作的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)
})
})
使用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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句