Reputation: 1742
I'm trying to loop over json data in react native.I want to create a new array with different key
and values
will be the looped json result.I've tried the following but nothing is working as expected.The format of json response will be the following.
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, …}
I want an array like this
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"
}
]
Following is the looping I've done but nothing is coming.Please help
.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)
})
})
Upvotes: 0
Views: 3924
Reputation: 71
Here is one possible solution. If I understand the question correctly you want to reformat and combine the section as the title and the unit(s) as the content...
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"
}
]
Upvotes: 0
Reputation: 50291
Use reduce
function and a variable to track the index of the accumulator array
Check it type is section then in the accumulator array push the value and update the variable value by 1.
If the type is unit then add the value in the content which is at the index defined by 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)
Upvotes: 1
Reputation: 537
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},
]
If resp is an object with a length and 0, 1, 2, ... keys, use Array.from(obj) to convert it to an object
If the resp is sorted (each unit belongs to the previous section)
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')
}
})
To trim the first word from the title use
function removeFirstWord(str) {
return str.replace(/^[^\s]+\s/, '')
}
The /symbols/ thing is called regular expression
so far it finds the first word
Upvotes: 2
Reputation: 2384
Here is a complete example code of what you want, try changing your data with the final loop and you will get your desire output :
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);
}
Upvotes: 1