我正在尝试在反应本机中循环json数据。我想创建一个具有不同key
的新数组,values
将是循环的 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)
})
})
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/事物称为正则表达式
- 字符串以(第一个 ^ 符号)开头,任何字符都需要
- 空格(空格=\s,[^某物]表示不是什么东西)
- 加号表示最后一部分可以重复 1 次或更多次
到目前为止,它找到了第一个单词
- \s 表示也替换单词后面的空格
使用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)
这是一个你想要的完整示例代码,尝试用最后一个循环更改你的数据,你会得到你想要的输出:
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);
}
这是一个可能的解决方案。如果我正确理解了这个问题,您想重新格式化并将该部分合并为标题,将单元合并为内容......
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"
}
]