Say I have the below Dataset.
╔═════════════╦═══════════════╦═══════╗
║ Category ║ Item ║ Color ║
╠═════════════╬═══════════════╬═══════╣
║ Electronics ║ Mobile ║ Black ║
║ Electronics ║ Mobile ║ Green ║
║ Electronics ║ Laptop ║ Black ║
║ HomeNeeds ║ VaccumCleaner ║ white ║
║ HomeNeeds ║ Refrigerator ║ Red ║
║ Wearable ║ AppleWatch ║ Red ║
╚═════════════╩═══════════════╩═══════╝
I want to transform this into SOMETHING like below JSON format so that I can load into a treeview control. What will be the best way to do that? The main difference is merging the same category or items! I can parse node to node in C#, check it with the previous node, merge it if it is same! and create it manually, but is there any other alternative instead of this long and complex process?
{
"Categories" : [
{"Electronics" : [
{"Mobile" : [
{"color":"Black"},
{"color":"Green"}
]},
{"Laptop":[
{"color":"Black"}
]}
]},
{"HomeNeeds":[
{"VaccumCleaner": [
{"color":"white"}
]},
{"Refrigerator":[
{"color": "Red"}
]}
]},
{"Wearable":[
{"Applewatch":[
{"color":"Red"}
]}
]}
]
}
Use an array.
var products = new Array(); // using new Array() to avoid mess
products =
[
[ // Home Needs
[
"Refrigerator",
"red",
"$500",
],
[
"VacuumCleaner",
"white",
"$50",
]
],
[ // Wearable
[
"Applewatch",
"Red",
"$14, 000",
],
],
]
Here is an example on how you would use this.
function getInfoOn(category,nameofappliance) { // 0 for category is home needs, etc
for (var i=0; i < products[category].length; i++) {
for(var l=0; l < products[i].length; l++) {
for (var b=0; b < i[category][l].length; b++) {
console.log('Name: '+ i[category][l][0]);
console.log('Price: '+i[category][l][2]);
}
}
}
}
Please note the above code is only for an example. It should function all right but I might have made a mistake while writing it. This was just to show my point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With