Reputation: 57
Good evening.
I have a CSV data is shown below.
level,label,price
1,menu1,3000
2,menu1_1,5000
2,menu1_2,6000
2,menu1_3,7000
1,menu2,8000
2,menu2_1,5000
3,menu2_1_1,5000
3,menu2_1_2,7000
2,menu2_2,6000
2,menu2_3,7000
1,menu3,9000
1,menu4,10000
I want to convert this data into json data as shown below. It is necessary that the recursive form should you write any javascript code I see?
[
{
"id": 1,
"label": "menu1",
"price": "3000",
"children": [
{
"id": 2,
"label": "menu1_1",
"price": "5000",
"children": []
},
{
"id": 3,
"label": "menu1_2",
"price": "6000",
"children": []
},
{
"id": 4,
"label": "menu1_1",
"price": "7000",
"children": []
}
]
},
{
"id": 5,
"label": "menu2",
"price": "8000",
"children": [
{
"id": 6,
"label": "menu2_1",
"price": "5000",
"children": [
{
"id": 7,
"label": "menu2_1_1",
"price": "5000",
"children": []
},
{
"id": 8,
"label": "menu2_1_2",
"price": "7000",
"children": []
}
]
},
{
"id": 9,
"label": "menu2_2",
"price": "6000",
"children": []
},
{
"id": 10,
"label": "menu2_3",
"price": "7000",
"children": []
}
]
},
{
"id": 11,
"label": "menu3",
"price": "9000",
"mnu_img": "",
"index": 46,
"children": []
},
{
"id": 12,
"label": "menu4",
"price": "10000",
"mnu_img": "",
"index": 50,
"children": []
}
]
However, I have a transformation import a CSV source. Note url: http://techslides.com/convert-csv-to-json-in-javascript
Thanks for your answer. but little problem is shown below.
i don't need array[0]
please help me.
Upvotes: 0
Views: 103
Reputation: 7113
First I parse the csv data to js objects:
var array = data.split("\n").map(function(row, index) {
var arr = row.split(",")
return {
id: index+1,
level: +arr[0],
label: arr[1],
price: arr[2],
children: []
}
})
Then I add a level 0, so that everything has a parent:
array.unshift({ level: 0, children: [] })
var parents = array.slice(0,1)
I loop over the data, comparing the level parameter to the previous one. I also keep the parents in a stack, with this level 0 parent at the bottom.
for(var i=1; i<array.length; i++) {
var prev = array[i-1]
var obj = array[i]
var p = parents[parents.length-1]
if(obj.level > prev.level) {
parents.push(prev)
p = prev
} else if (obj.level < prev.level) {
do {
p = parents.pop()
} while(obj.level < p.level)
p = parents[parents.length-1]
}
p.children.push(obj)
}
Finally I read out the result
var result = parents[0].children
console.log(result)
Working example: http://jsbin.com/zexiyigili/1/edit?js,console
Upvotes: 1