Sort Data based on mla names - javascript

Hi I have this below Json Data
How i can show only mla name list in the UI and based on which mla has got more votes?
How i can achieve this one? help me with this
Thank you
[
{
"id": 6,
"mla": [
{
"id": 16,
"votes": 1,
"name": "Shrimant",
"image": "http://localhost:8000/media/uploads/images/assignment_image.png",
"category": "MLA",
"zipcode": 591320,
"age": 49,
"email": "shrimant#gmail.com",
"contact_number": 58966663144,
"party": 1,
"state": 4,
"district": 5,
"constituency": 6
},
{
"id": 19,
"votes": 3,
"name": "Shetal Patil",
"image": "http://localhost:8000/media/uploads/images/7_oHBWq6E.png",
"category": "MLA",
"zipcode": 591320,
"age": 35,
"email": "shetal#gmail.com",
"contact_number": 8523697410,
"party": 2,
"state": 4,
"district": 5,
"constituency": 6
},
{
"id": 20,
"votes": 2,
"name": "Raju Kage",
"image": "http://localhost:8000/media/uploads/images/new1_MIaR3xQ.png",
"category": "MLA",
"zipcode": 591320,
"age": 50,
"email": "raju#gmail.com",
"contact_number": 8963257410,
"party": 3,
"state": 4,
"district": 5,
"constituency": 6
}
],
"state": "Karanataka",
"state_id": 4,
"district": "Belgavi",
"district_id": 5,
"constituency": "Kagwad"
},
{
"id": 7,
"mla": [
{
"id": 9,
"votes": 1,
"name": "Chandra Metal Mart",
"image": "http://localhost:8000/media/uploads/images/2.png",
"category": "MLA",
"zipcode": 638103,
"age": 23,
"email": "raju#gmail.com",
"contact_number": 4294264242,
"party": 1,
"state": 4,
"district": 5,
"constituency": 7
},
{
"id": 10,
"votes": 3,
"name": "Vaibhav",
"image": "http://localhost:8000/media/uploads/images/4.png",
"category": "MLA",
"zipcode": 638103,
"age": 34,
"email": "duryodhan#gmail.com",
"contact_number": 4294264242,
"party": 2,
"state": 4,
"district": 5,
"constituency": 7
},
{
"id": 12,
"votes": 2,
"name": "MLA 1",
"image": "http://localhost:8000/media/uploads/images/7.png",
"category": "MLA",
"zipcode": 638103,
"age": 23,
"email": "vaibhav#df.com",
"contact_number": 4294264242,
"party": 3,
"state": 4,
"district": 5,
"constituency": 7
},
{
"id": 21,
"votes": 1,
"name": "Gajanan",
"image": "http://localhost:8000/media/uploads/images/WhatsApp_Image_2020-11-04_at_7.56.56_PM.jpeg",
"category": "MLA",
"zipcode": 638103,
"age": 45,
"email": "can1#gmail.com",
"contact_number": 4294264242,
"party": 5,
"state": 4,
"district": 5,
"constituency": 7
},
{
"id": 22,
"votes": 1,
"name": "Pranav Singh",
"image": "http://localhost:8000/media/uploads/images/WhatsApp_Image_2020-11-04_at_7.56.56_PM_W9hWtbF.jpeg",
"category": "MLA",
"zipcode": 638103,
"age": 25,
"email": "raju#kage.com",
"contact_number": 4294264242,
"party": 6,
"state": 4,
"district": 5,
"constituency": 7
}
],
"state": "Karanataka",
"state_id": 4,
"district": "Belgavi",
"district_id": 5,
"constituency": "Chikodi"
},
{
"id": 8,
"mla": [],
"state": "Karanataka",
"state_id": 4,
"district": "Dharwad",
"district_id": 6,
"constituency": "Navlgund"
},
{
"id": 9,
"mla": [
{
"id": 11,
"votes": 3,
"name": "Shetter",
"image": "http://localhost:8000/media/uploads/images/images_2.jpg",
"category": "MLA",
"zipcode": 638103,
"age": 23,
"email": "raju#gmail.com",
"contact_number": 4294264242,
"party": 1,
"state": 4,
"district": 6,
"constituency": 9
},
{
"id": 14,
"votes": 0,
"name": "Ramulu",
"image": "http://localhost:8000/media/uploads/images/2_mK5SuIZ.png",
"category": "MLA",
"zipcode": 638103,
"age": 27,
"email": "raju#kage.com",
"contact_number": 4294264242,
"party": 3,
"state": 4,
"district": 6,
"constituency": 9
},
{
"id": 15,
"votes": 1,
"name": "Ravi",
"image": "http://localhost:8000/media/uploads/images/new1.png",
"category": "MLA",
"zipcode": 638103,
"age": 27,
"email": "raju#kage.com",
"contact_number": 4294264242,
"party": 2,
"state": 4,
"district": 6,
"constituency": 9
}
],
"state": "Karanataka",
"state_id": 4,
"district": "Dharwad",
"district_id": 6,
"constituency": "Kalghatgi"
},
{
"id": 10,
"mla": [],
"state": "Tamil Nadu",
"state_id": 5,
"district": "Tripur",
"district_id": 7,
"constituency": "tripur1"
},
{
"id": 11,
"mla": [],
"state": "Tamil Nadu",
"state_id": 5,
"district": "Tripur",
"district_id": 7,
"constituency": "tripur2"
},
{
"id": 12,
"mla": [],
"state": "Maharastra",
"state_id": 6,
"district": "Karad",
"district_id": 10,
"constituency": "karad1"
},
{
"id": 13,
"mla": [
{
"id": 17,
"votes": 2,
"name": "Sashikala Jolle",
"image": "http://localhost:8000/media/uploads/images/2_Plb3dTO.png",
"category": "MLA",
"zipcode": 638103,
"age": 50,
"email": "jolle#gmail.com",
"contact_number": 4294264242,
"party": 1,
"state": 4,
"district": 5,
"constituency": 13
},
{
"id": 18,
"votes": 0,
"name": "MLA 23",
"image": "http://localhost:8000/media/uploads/images/3.png",
"category": "MLA",
"zipcode": 638103,
"age": 23,
"email": "raju#gmail.com",
"contact_number": 4294264242,
"party": 2,
"state": 4,
"district": 5,
"constituency": 13
}
],
"state": "Karanataka",
"state_id": 4,
"district": "Belgavi",
"district_id": 5,
"constituency": "Nippani"
},
{
"id": 14,
"mla": [],
"state": "Karanataka",
"state_id": 4,
"district": "Belgavi",
"district_id": 5,
"constituency": "Gokak"
},
{
"id": 15,
"mla": [],
"state": "Karanataka",
"state_id": 4,
"district": "Belgavi",
"district_id": 5,
"constituency": "Bailhongal"
},
{
"id": 16,
"mla": [],
"state": "Karanataka",
"state_id": 4,
"district": "Belgavi",
"district_id": 5,
"constituency": "Kudachi"
},
{
"id": 17,
"mla": [],
"state": "Karanataka",
"state_id": 4,
"district": "Belgavi",
"district_id": 5,
"constituency": "Raybag"
},
{
"id": 18,
"mla": [],
"state": "Karanataka",
"state_id": 4,
"district": "Dharwad",
"district_id": 6,
"constituency": "Kundgol"
},
{
"id": 19,
"mla": [],
"state": "Karanataka",
"state_id": 4,
"district": "Dharwad",
"district_id": 6,
"constituency": "Navalgund"
},
{
"id": 20,
"mla": [],
"state": "Karanataka",
"state_id": 4,
"district": "Bangalore",
"district_id": 11,
"constituency": "Bangalore-east"
},
{
"id": 21,
"mla": [],
"state": "Karanataka",
"state_id": 4,
"district": "Bangalore",
"district_id": 11,
"constituency": "Bangalore-west"
},
{
"id": 22,
"mla": [],
"state": "Karanataka",
"state_id": 4,
"district": "Bangalore",
"district_id": 11,
"constituency": "Bangalore-south"
}
]

Use the following code
var mlas = []; // WHICH STORES LIST OF MLAS WITH HIGHEST VOTED
// PICKING MLA DATA FROM THE JSON
jsonData.forEach(e => {
mlas = mlas.concat(e.mla);
});
//SORTING ON VOTES
var sorted = mlas.sort((a,b) => b.votes - a.votes);

You could map, filter, flatten and sort the data to get the result set you need and then use JavaScript to create the list. Working solution below.
<html>
<body>
<div>
<ul id="mla-list">
</ul>
<div>
<script>
const data = [{ "id": 6, "mla": [{ "id": 16, "votes": 1, "name": "Shrimant", "image": "http://localhost:8000/media/uploads/images/assignment_image.png", "category": "MLA", "zipcode": 591320, "age": 49, "email": "shrimant#gmail.com", "contact_number": 58966663144, "party": 1, "state": 4, "district": 5, "constituency": 6 }, { "id": 19, "votes": 3, "name": "Shetal Patil", "image": "http://localhost:8000/media/uploads/images/7_oHBWq6E.png", "category": "MLA", "zipcode": 591320, "age": 35, "email": "shetal#gmail.com", "contact_number": 8523697410, "party": 2, "state": 4, "district": 5, "constituency": 6 }, { "id": 20, "votes": 2, "name": "Raju Kage", "image": "http://localhost:8000/media/uploads/images/new1_MIaR3xQ.png", "category": "MLA", "zipcode": 591320, "age": 50, "email": "raju#gmail.com", "contact_number": 8963257410, "party": 3, "state": 4, "district": 5, "constituency": 6 }], "state": "Karanataka", "state_id": 4, "district": "Belgavi", "district_id": 5, "constituency": "Kagwad" }, { "id": 7, "mla": [{ "id": 9, "votes": 1, "name": "Chandra Metal Mart", "image": "http://localhost:8000/media/uploads/images/2.png", "category": "MLA", "zipcode": 638103, "age": 23, "email": "raju#gmail.com", "contact_number": 4294264242, "party": 1, "state": 4, "district": 5, "constituency": 7 }, { "id": 10, "votes": 3, "name": "Vaibhav", "image": "http://localhost:8000/media/uploads/images/4.png", "category": "MLA", "zipcode": 638103, "age": 34, "email": "duryodhan#gmail.com", "contact_number": 4294264242, "party": 2, "state": 4, "district": 5, "constituency": 7 }, { "id": 12, "votes": 2, "name": "MLA 1", "image": "http://localhost:8000/media/uploads/images/7.png", "category": "MLA", "zipcode": 638103, "age": 23, "email": "vaibhav#df.com", "contact_number": 4294264242, "party": 3, "state": 4, "district": 5, "constituency": 7 }, { "id": 21, "votes": 1, "name": "Gajanan", "image": "http://localhost:8000/media/uploads/images/WhatsApp_Image_2020-11-04_at_7.56.56_PM.jpeg", "category": "MLA", "zipcode": 638103, "age": 45, "email": "can1#gmail.com", "contact_number": 4294264242, "party": 5, "state": 4, "district": 5, "constituency": 7 }, { "id": 22, "votes": 1, "name": "Pranav Singh", "image": "http://localhost:8000/media/uploads/images/WhatsApp_Image_2020-11-04_at_7.56.56_PM_W9hWtbF.jpeg", "category": "MLA", "zipcode": 638103, "age": 25, "email": "raju#kage.com", "contact_number": 4294264242, "party": 6, "state": 4, "district": 5, "constituency": 7 }], "state": "Karanataka", "state_id": 4, "district": "Belgavi", "district_id": 5, "constituency": "Chikodi" }, { "id": 8, "mla": [], "state": "Karanataka", "state_id": 4, "district": "Dharwad", "district_id": 6, "constituency": "Navlgund" }, { "id": 9, "mla": [{ "id": 11, "votes": 3, "name": "Shetter", "image": "http://localhost:8000/media/uploads/images/images_2.jpg", "category": "MLA", "zipcode": 638103, "age": 23, "email": "raju#gmail.com", "contact_number": 4294264242, "party": 1, "state": 4, "district": 6, "constituency": 9 }, { "id": 14, "votes": 0, "name": "Ramulu", "image": "http://localhost:8000/media/uploads/images/2_mK5SuIZ.png", "category": "MLA", "zipcode": 638103, "age": 27, "email": "raju#kage.com", "contact_number": 4294264242, "party": 3, "state": 4, "district": 6, "constituency": 9 }, { "id": 15, "votes": 1, "name": "Ravi", "image": "http://localhost:8000/media/uploads/images/new1.png", "category": "MLA", "zipcode": 638103, "age": 27, "email": "raju#kage.com", "contact_number": 4294264242, "party": 2, "state": 4, "district": 6, "constituency": 9 }], "state": "Karanataka", "state_id": 4, "district": "Dharwad", "district_id": 6, "constituency": "Kalghatgi" }, { "id": 10, "mla": [], "state": "Tamil Nadu", "state_id": 5, "district": "Tripur", "district_id": 7, "constituency": "tripur1" }, { "id": 11, "mla": [], "state": "Tamil Nadu", "state_id": 5, "district": "Tripur", "district_id": 7, "constituency": "tripur2" }, { "id": 12, "mla": [], "state": "Maharastra", "state_id": 6, "district": "Karad", "district_id": 10, "constituency": "karad1" }, { "id": 13, "mla": [{ "id": 17, "votes": 2, "name": "Sashikala Jolle", "image": "http://localhost:8000/media/uploads/images/2_Plb3dTO.png", "category": "MLA", "zipcode": 638103, "age": 50, "email": "jolle#gmail.com", "contact_number": 4294264242, "party": 1, "state": 4, "district": 5, "constituency": 13 }, { "id": 18, "votes": 0, "name": "MLA 23", "image": "http://localhost:8000/media/uploads/images/3.png", "category": "MLA", "zipcode": 638103, "age": 23, "email": "raju#gmail.com", "contact_number": 4294264242, "party": 2, "state": 4, "district": 5, "constituency": 13 }], "state": "Karanataka", "state_id": 4, "district": "Belgavi", "district_id": 5, "constituency": "Nippani" }, { "id": 14, "mla": [], "state": "Karanataka", "state_id": 4, "district": "Belgavi", "district_id": 5, "constituency": "Gokak" }, { "id": 15, "mla": [], "state": "Karanataka", "state_id": 4, "district": "Belgavi", "district_id": 5, "constituency": "Bailhongal" }, { "id": 16, "mla": [], "state": "Karanataka", "state_id": 4, "district": "Belgavi", "district_id": 5, "constituency": "Kudachi" }, { "id": 17, "mla": [], "state": "Karanataka", "state_id": 4, "district": "Belgavi", "district_id": 5, "constituency": "Raybag" }, { "id": 18, "mla": [], "state": "Karanataka", "state_id": 4, "district": "Dharwad", "district_id": 6, "constituency": "Kundgol" }, { "id": 19, "mla": [], "state": "Karanataka", "state_id": 4, "district": "Dharwad", "district_id": 6, "constituency": "Navalgund" }, { "id": 20, "mla": [], "state": "Karanataka", "state_id": 4, "district": "Bangalore", "district_id": 11, "constituency": "Bangalore-east" }, { "id": 21, "mla": [], "state": "Karanataka", "state_id": 4, "district": "Bangalore", "district_id": 11, "constituency": "Bangalore-west" }, { "id": 22, "mla": [], "state": "Karanataka", "state_id": 4, "district": "Bangalore", "district_id": 11, "constituency": "Bangalore-south" }];
const mlaNames = data.map(d => d.mla)
.filter(mla => mla.length > 0)
.flat()
.sort((mla1, mla2) => mla2.votes - mla1.votes)
.map(mla => mla.name);
const list = document.getElementById("mla-list");
mlaNames.forEach(mlaName => {
const li = document.createElement("li");
li.innerText = mlaName;
list.appendChild(li);
});
</script>
</body>

Related

Json data to javaScript Treeview

hello there is a json data as below.
var arr = [{
"ID": 1,
"parentID": 0,
"Phone": "(403) 125-2552",
"City": "Coevorden",
"Name": "Grady"
}, {
"ID": 2,
"parentID": 0,
"Phone": "(979) 486-1932",
"City": "Chełm",
"Name": "Scarlet"
}, {
"ID": 3,
"parentID": 0,
"Phone": "(573) 685-8350",
"City": "Wardha",
"Name": "Adria"
}, {
"ID": 4,
"parentID": 3,
"Phone": "(630) 292-9737",
"City": "Villers-la-Loue",
"Name": "Xerxes"
}, {
"ID": 5,
"parentID": 0,
"Phone": "(755) 968-6539",
"City": "Gönen",
"Name": "Madeson"
}, {
"ID": 6,
"parentID": 5,
"Phone": "(644) 892-5485",
"City": "Timkur",
"Name": "Rae"
}, {
"ID": 7,
"parentID": 0,
"Phone": "(896) 297-6568",
"City": "Louvain-la-Neuve",
"Name": "Celeste"
}, {
"ID": 8,
"parentID": 5,
"Phone": "(168) 452-3538",
"City": "Worksop",
"Name": "Rowan"
}, {
"ID": 9,
"parentID": 5,
"Phone": "(873) 337-9560",
"City": "Bad Neuenahr-Ahrweiler",
"Name": "Kendall"
}, {
"ID": 10,
"parentID": 0,
"Phone": "(450) 579-0491",
"City": "MIDdelburg",
"Name": "Madaline"
}, {
"ID": 11,
"parentID": 0,
"Phone": "(111) 162-2502",
"City": "Birecik",
"Name": "Chandler"
}, {
"ID": 12,
"parentID": 8,
"Phone": "(712) 483-3905",
"City": "Courbevoie",
"Name": "Craig"
}, {
"ID": 13,
"parentID": 8,
"Phone": "(872) 499-5833",
"City": "Cuccaro Vetere",
"Name": "Basia"
}, {
"ID": 14,
"parentID": 6,
"Phone": "(724) 797-0077",
"City": "Portree",
"Name": "Elmo"
}, {
"ID": 15,
"parentID": 5,
"Phone": "(366) 967-0433",
"City": "Dublin",
"Name": "Cairo"
}, {
"ID": 16,
"parentID": 11,
"Phone": "(147) 708-7321",
"City": "Rivière-du-Loup",
"Name": "Mannix"
}, {
"ID": 17,
"parentID": 0,
"Phone": "(407) 519-9894",
"City": "Roubaix",
"Name": "Justine"
}]
.
.
.
I wanted to make a treeview of this data and I got a result like the one below. No problem, it works properly.
[
{
"ID": 1,
"parentID": 0,
"Phone": "(403) 125-2552",
"City": "Coevorden",
"Name": "Grady"
},
{
"ID": 2,
"parentID": 0,
"Phone": "(979) 486-1932",
"City": "Chełm",
"Name": "Scarlet",
"children": [
{
"ID": 30,
"parentID": 2,
"Phone": "(641) 756-7073",
"City": "Harrison Hot Springs",
"Name": "Hamilton",
"children": [
{
"ID": 54,
"parentID": 30,
"Phone": "(800) 876-5942",
"City": "Ribnitz-Damgarten",
"Name": "Kelsie",
"children": [
{
"ID": 62,
"parentID": 54,
"Phone": "(523) 159-2911",
"City": "Biała Podlaska",
"Name": "Clio"
}
]
},
{
"ID": 87,
"parentID": 30,
"Phone": "(500) 895-9220",
"City": "Piracicaba",
"Name": "Maya"
}
]
},
{
"ID": 40,
"parentID": 2,
"Phone": "(921) 336-7339",
"City": "Namur",
"Name": "Lionel"
},
{
"ID": 43,
"parentID": 2,
"Phone": "(410) 695-8540",
"City": "Saint-Laurent",
"Name": "Deanna",
"children": [
{
"ID": 63,
"parentID": 43,
"Phone": "(475) 190-5102",
"City": "Nicoya",
"Name": "Nola"
},
{
"ID": 98,
"parentID": 43,
"Phone": "(268) 572-5059",
"City": "San Marcello Pistoiese",
"Name": "Marny"
}
]
}
]
},
{
"ID": 3,
"parentID": 0,
"Phone": "(573) 685-8350",
"City": "Wardha",
"Name": "Adria",
"children": [
{
"ID": 4,
"parentID": 3,
"Phone": "(630) 292-9737",
"City": "Villers-la-Loue",
"Name": "Xerxes",
"children": [
{
"ID": 44,
"parentID": 4,
"Phone": "(287) 866-8953",
"City": "Fiuminata",
"Name": "Darius",
"children": [
{
"ID": 47,
"parentID": 44,
"Phone": "(779) 411-0381",
"City": "Pontedera",
"Name": "Harding",
"children": [
{
"ID": 92,
"parentID": 47,
"Phone": "(925) 263-0254",
"City": "Curacaví",
"Name": "Aristotle"
}
]
}
]
},
{
"ID": 56,
"parentID": 4,
"Phone": "(963) 719-2718",
"City": "Gore",
"Name": "Rafael"
}
]
},
{
"ID": 58,
"parentID": 3,
"Phone": "(464) 318-7548",
"City": "Curepto",
"Name": "Leila"
}
]
.
.
.
My main question is parentID: I don't want to write parentID to objects that write 0. But when I remove the places that say parentID: 0, it doesn't work properly. Can you help?
The code I run is:
tree = function(array) {
var o = {
ID: 0
}
function arrGet(o) {
if (Array.isArray(o.children)) {
o.children.forEach(arrGet);
}
}
array.forEach(function(a) {
o[a.ID] = o[a.ID] || {
ID: a.ID,
parentID: a.parentID,
Phone: a.Phone,
City: a.City,
Name: a.Name
};
a.children = o[a.ID].children;
o[a.parentID] = o[a.parentID] || {
ID: a.parentID
};
o[a.parentID].children = o[a.parentID].children || [];
o[a.parentID].children.push(o[a.ID]);
});
arrGet(o[0]);
return o[0].children;
}(arr);
document.writeln('<pre>' + JSON.stringify(tree, 0, 4) + '</pre>');
just find the way inside the tree, based on origin array...
Full code:
/*--------------------------------------------------------*\
| treeMaker : JSON [Array of obj] to Treeview (function) |
| |
| input array objets must be like { ID,[ parentID ] ...} |
\* -------------------------------------------------------*/
const treeMaker = arr =>
arr.reduce((tree,{parentID,...useful},_,Origin)=>
{
if (!parentID) tree.push({...useful}) // direct case!
else
{
let path = { children: tree } // path for insert
, road = [ Origin.find(x=>x.ID===parentID) ] // every road has an end
;
while(!!road[0].parentID) // as long as a parentID property exist
{
road.unshift(Origin.find(x=>x.ID===road[0].parentID)) // get road origin
}
for(let way of road) // make your way by following the road
{
path = path.children.find(x=>x.ID===way.ID) // change the path to children
}
if (!path.children) path.children = [] // if not exist, add children array
;
path.children.push({...useful}) // copy all useful items
}
return tree // back to the trees!
},[])
/*--------------------------------------------------------*/
// test part
const myArr =
[ { ID: 1, Phone: '(403) 125-2552', City: 'Coevorden', Name: 'Grady' }
, { ID: 2, Phone: '(979) 486-1932', City: 'Chełm', Name: 'Scarlet' }
, { ID: 3, Phone: '(573) 685-8350', City: 'Wardha', Name: 'Adria' }
, { ID: 4, parentID: 3, Phone: '(630) 292-9737', City: 'Villers-la-Loue', Name: 'Xerxes' }
, { ID: 5, Phone: '(755) 968-6539', City: 'Gönen', Name: 'Madeson' }
, { ID: 6, parentID: 5, Phone: '(644) 892-5485', City: 'Timkur', Name: 'Rae' }
, { ID: 7, Phone: '(896) 297-6568', City: 'Louvain-la-Neuve', Name: 'Celeste' }
, { ID: 8, parentID: 5, Phone: '(168) 452-3538', City: 'Worksop', Name: 'Rowan' }
, { ID: 9, parentID: 5, Phone: '(873) 337-9560', City: 'Bad Neuenahr-Ahrweiler', Name: 'Kendall' }
, { ID: 10, Phone: '(450) 579-0491', City: 'MIDdelburg', Name: 'Madaline' }
, { ID: 11, Phone: '(111) 162-2502', City: 'Birecik', Name: 'Chandler' }
, { ID: 12, parentID: 8, Phone: '(712) 483-3905', City: 'Courbevoie', Name: 'Craig' }
, { ID: 13, parentID: 8, Phone: '(872) 499-5833', City: 'Cuccaro Vetere', Name: 'Basia' }
, { ID: 14, parentID: 6, Phone: '(724) 797-0077', City: 'Portree', Name: 'Elmo' }
, { ID: 15, parentID: 5, Phone: '(366) 967-0433', City: 'Dublin', Name: 'Cairo' }
, { ID: 16, parentID: 11, Phone: '(147) 708-7321', City: 'Rivière-du-Loup', Name: 'Mannix' }
, { ID: 17, Phone: '(407) 519-9894', City: 'Roubaix', Name: 'Justine' }
, { ID: 18, parentID: 14, Phone: '(938) 793-5446', City: 'Eugene', Name: 'Dahlia' }
, { ID: 19, parentID: 5, Phone: '(425) 682-2189', City: 'Salisbury', Name: 'Irene' }
, { ID: 20, parentID: 12, Phone: '(351) 187-8200', City: 'Garaguso', Name: 'Trevor' }
, { ID: 21, Phone: '(601) 944-5214', City: 'Pointe-au-Pic', Name: 'Iris' }
, { ID: 22, parentID: 20, Phone: '(479) 532-6127', City: 'Salt Lake City', Name: 'Fleur' }
, { ID: 23, parentID: 19, Phone: '(339) 973-1695', City: 'Meldert', Name: 'Hayley' }
, { ID: 24, parentID: 11, Phone: '(946) 766-1649', City: 'Corral', Name: 'Baker' }
, { ID: 25, Phone: '(964) 413-7033', City: 'Joliet', Name: 'Leo' }
, { ID: 26, parentID: 7, Phone: '(898) 476-0059', City: 'Burntisland', Name: 'Rigel' }
]
const myTree = treeMaker ( myArr )
document.write('<pre>myTree:\n')
document.write(JSON.stringify(myTree,0,2))
document.write('</pre>')
In this algorithm, the destructuring assignment is used on each element of the original table, as follows:
let element1 = { ID:6, parentID:5, City:'Timkur', Name:'Rae' }
let {parentID, ...useful} = element1 // destructuring assignment
console.log( parentID ) // return 5
console.log( useful ) // return object { ID:6, City:'Timkur', Name:'Rae' }
console.log ( !parentID ) // return false
without parentID property:
let element2 = { ID:7, City:'Louvain-la-Neuve', Name: 'Celeste' }
let {parentID, ...useful} = element2 // destructuring assignment
console.log( parentID ) // undefined
console.log( useful ) // return object { ID:7, ....
console.log ( !parentID ) // return true
In this code the destructuring assignment is directly used inside the argument list of the array method reduce (see further)
About the use of the Array.reduce method (see mdn for more details):
const arr_tree = arr.reduce(function(tree,curr,idx,Origin) {…}, initilial_tree);
same as arrow notation:
a) const arr_tree = arr.reduce((tree,curr,_,Origin)=>{…}, []);
b) const arr_tree = arr.reduce((tree,{parentID,...useful},_,Origin)=>
Arrguments:
tree, array under construction (initialized by initilial_tree, here=[] =>empty array), this element must be returned at each iteration
curr: the current element (as in a loop on the array), **used in an destructuring assignment
{parentID,...useful} = curr ( please compare a) and b) )
idx: the index of the element (curr) on the array (not useful here and replaced by _)
Origin: the original table used by the method
the algorithm:
for any element with a parentID, its parent must be found in the tree under construction.
That is, for an X element with a parentID there is an X-1 element with that ID.
And if this X-1 element has itself a ParentID, there is also another X-2 element with this ID.
And so on, until we find an X-n element that has no ParentID.
This X-N element is directly at the root of the result array.
All that remains is to follow the reverse path in the tree structure under construction:
we look for the position Xn at the level of its root, then on this one the element X- (n-1) among its children, until finding that of the element X-1 where we can add the element X in the list of its children.
Making sure to add an empty list of children, if X-1 had no children yet.
There are therefore 2 parts:
1- go up the road from X-1 to the X-n elements using the origin table
let road = [ Origin.find(x=>x.ID===parentID) ] // every road has an end
while(!!road[0].parentID) // as long as a parentID property exist
{
road.unshift(Origin.find(x=>x.ID===road[0].parentID)) // get road origin
}
if we start from element X = { ID: 12, parentID: 8, ... Name: 'Craig'} (where the parentID value is 8)
the result is :
road = [ { ID: 5, ... Name: 'Madeson' }
, { ID: 8, parentID: 5,... Name: 'Rowan' }
]
note 1:
the use of the array.unshift() method to add the elements from the top
/ unlike the array.push() method, the last element entered is therefore in position zero,
which allows the test to be passed
(!!road[0].parentID)
with always an index value at zero.
...For the double exclamation mark look here
note 2:
the road array only contains "pointers" to the objects of the original array.
2- find the path of element X-1 in tree structure under construction
let path = { children: tree } // path for insert
for(let way of road) // make your way by following the road
{
path = path.children.find(x=>x.ID===way.ID) // change the path to children
}
note X: I use my sort of Whitesmiths style code formatting for years
for info, it's look like that:
├─1_Grady
├─2_Scarlet
├─3_Adria─┐
│ └─4_Xerxes
├─5_Madeson─┐
│ ├─6_Rae─┐
│ │ └─14_Elmo─┐
│ │ └─18_Dahlia
│ ├─8_Rowan─┐
│ │ ├─12_Craig─┐
│ │ │ └─20_Trevor─┐
│ │ │ └─22_Fleur
│ │ └─13_Basia
│ ├─9_Kendall
│ ├─15_Cairo
│ └─19_Irene─┐
│ └─23_Hayley
├─7_Celeste─┐
│ └─26_Rigel
├─10_Madaline
├─11_Chandler─┐
│ ├─16_Mannix
│ └─24_Baker
├─17_Justine
├─21_Iris
└─25_Leo
What you can do is to use the delete operator when parentID is equal to 0. This will delete the property from the object, hence not displaying it.
var arr = [{
"ID": 1,
"parentID": 0,
"Phone": "(403) 125-2552",
"City": "Coevorden",
"Name": "Grady"
}, {
"ID": 2,
"parentID": 0,
"Phone": "(979) 486-1932",
"City": "Chełm",
"Name": "Scarlet"
}, {
"ID": 3,
"parentID": 0,
"Phone": "(573) 685-8350",
"City": "Wardha",
"Name": "Adria"
}, {
"ID": 4,
"parentID": 3,
"Phone": "(630) 292-9737",
"City": "Villers-la-Loue",
"Name": "Xerxes"
}, {
"ID": 5,
"parentID": 0,
"Phone": "(755) 968-6539",
"City": "Gönen",
"Name": "Madeson"
}, {
"ID": 6,
"parentID": 5,
"Phone": "(644) 892-5485",
"City": "Timkur",
"Name": "Rae"
}, {
"ID": 7,
"parentID": 0,
"Phone": "(896) 297-6568",
"City": "Louvain-la-Neuve",
"Name": "Celeste"
}, {
"ID": 8,
"parentID": 5,
"Phone": "(168) 452-3538",
"City": "Worksop",
"Name": "Rowan"
}, {
"ID": 9,
"parentID": 5,
"Phone": "(873) 337-9560",
"City": "Bad Neuenahr-Ahrweiler",
"Name": "Kendall"
}, {
"ID": 10,
"parentID": 0,
"Phone": "(450) 579-0491",
"City": "MIDdelburg",
"Name": "Madaline"
}, {
"ID": 11,
"parentID": 0,
"Phone": "(111) 162-2502",
"City": "Birecik",
"Name": "Chandler"
}, {
"ID": 12,
"parentID": 8,
"Phone": "(712) 483-3905",
"City": "Courbevoie",
"Name": "Craig"
}, {
"ID": 13,
"parentID": 8,
"Phone": "(872) 499-5833",
"City": "Cuccaro Vetere",
"Name": "Basia"
}, {
"ID": 14,
"parentID": 6,
"Phone": "(724) 797-0077",
"City": "Portree",
"Name": "Elmo"
}, {
"ID": 15,
"parentID": 5,
"Phone": "(366) 967-0433",
"City": "Dublin",
"Name": "Cairo"
}, {
"ID": 16,
"parentID": 11,
"Phone": "(147) 708-7321",
"City": "Rivière-du-Loup",
"Name": "Mannix"
}, {
"ID": 17,
"parentID": 0,
"Phone": "(407) 519-9894",
"City": "Roubaix",
"Name": "Justine"
}];
tree = function(array) {
var o = {
ID: 0
}
function arrGet(o) {
if (Array.isArray(o.children)) {
o.children.forEach(arrGet);
}
}
array.forEach(function(a) {
o[a.ID] = o[a.ID] || {
ID: a.ID,
parentID: a.parentID,
Phone: a.Phone,
City: a.City,
Name: a.Name
};
if(a.parentID === 0)
delete o[a.ID].parentID;
a.children = o[a.ID].children;
o[a.parentID] = o[a.parentID] || {
ID: a.parentID
};
o[a.parentID].children = o[a.parentID].children || [];
o[a.parentID].children.push(o[a.ID]);
});
arrGet(o[0]);
return o[0].children;
}(arr);
document.writeln('<pre>' + JSON.stringify(tree, 0, 4) + '</pre>');
var arr = [{
"ID": 1,
"Phone": "(403) 125-2552",
"City": "Coevorden",
"Name": "Grady"
}, {
"ID": 2,
"Phone": "(979) 486-1932",
"City": "Chełm",
"Name": "Scarlet"
}, {
"ID": 3,
"Phone": "(573) 685-8350",
"City": "Wardha",
"Name": "Adria"
}, {
"ID": 4,
"parentID": 3,
"Phone": "(630) 292-9737",
"City": "Villers-la-Loue",
"Name": "Xerxes"
}, {
"ID": 5,
"Phone": "(755) 968-6539",
"City": "Gönen",
"Name": "Madeson"
}, {
"ID": 6,
"parentID": 5,
"Phone": "(644) 892-5485",
"City": "Timkur",
"Name": "Rae"
}, {
"ID": 7,
"Phone": "(896) 297-6568",
"City": "Louvain-la-Neuve",
"Name": "Celeste"
}, {
"ID": 8,
"parentID": 5,
"Phone": "(168) 452-3538",
"City": "Worksop",
"Name": "Rowan"
}, {
"ID": 9,
"parentID": 5,
"Phone": "(873) 337-9560",
"City": "Bad Neuenahr-Ahrweiler",
"Name": "Kendall"
}, {
"ID": 10,
"Phone": "(450) 579-0491",
"City": "MIDdelburg",
"Name": "Madaline"
}, {
"ID": 11,
"Phone": "(111) 162-2502",
"City": "Birecik",
"Name": "Chandler"
}, {
"ID": 12,
"parentID": 8,
"Phone": "(712) 483-3905",
"City": "Courbevoie",
"Name": "Craig"
}, {
"ID": 13,
"parentID": 8,
"Phone": "(872) 499-5833",
"City": "Cuccaro Vetere",
"Name": "Basia"
}, {
"ID": 14,
"parentID": 6,
"Phone": "(724) 797-0077",
"City": "Portree",
"Name": "Elmo"
}, {
"ID": 15,
"parentID": 5,
"Phone": "(366) 967-0433",
"City": "Dublin",
"Name": "Cairo"
}, {
"ID": 16,
"parentID": 11,
"Phone": "(147) 708-7321",
"City": "Rivière-du-Loup",
"Name": "Mannix"
}, {
"ID": 17,
"Phone": "(407) 519-9894",
"City": "Roubaix",
"Name": "Justine"
}, {
"ID": 18,
"parentID": 14,
"Phone": "(938) 793-5446",
"City": "Eugene",
"Name": "Dahlia"
}, {
"ID": 19,
"parentID": 5,
"Phone": "(425) 682-2189",
"City": "Salisbury",
"Name": "Irene"
}, {
"ID": 20,
"parentID": 12,
"Phone": "(351) 187-8200",
"City": "Garaguso",
"Name": "Trevor"
}, {
"ID": 21,
"Phone": "(601) 944-5214",
"City": "Pointe-au-Pic",
"Name": "Iris"
}, {
"ID": 22,
"parentID": 20,
"Phone": "(479) 532-6127",
"City": "Salt Lake City",
"Name": "Fleur"
}, {
"ID": 23,
"parentID": 19,
"Phone": "(339) 973-1695",
"City": "Meldert",
"Name": "Hayley"
}, {
"ID": 24,
"parentID": 11,
"Phone": "(946) 766-1649",
"City": "Corral",
"Name": "Baker"
}, {
"ID": 25,
"Phone": "(964) 413-7033",
"City": "Joliet",
"Name": "Leo"
}, {
"ID": 26,
"parentID": 7,
"Phone": "(898) 476-0059",
"City": "Burntisland",
"Name": "Rigel"
}]
original data like this

How to create csv/excel file from response data reactjs

I have response data like below:
{
"Aerospace": [
{
"id": 62,
"branch": "Aerospace",
"classification": "Einstufungen 2",
"theme": "Produktentwicklung",
"branch_id": 1,
"classification_id": 1,
"projectno": "510",
"project_id": 52,
"theme_id": 6,
"projectname": "test 22",
"comment": "",
"customername": "test 12",
"lead1id": 14,
"lead1name": "DateTest",
"lead1percent": "1000000000.0",
"lead2id": 11,
"lead2name": "logintest",
"lead2percent": "2000000000.0",
"lead3id": 16,
"lead3name": "jomo",
"lead3percent": "3000000000.0",
"leadplan_probability": "100.0",
"leadplan_plan2": "200.0",
"leadplan_plan3": "300.0",
"leadplan_addcosts": "500.0",
"leadplan_fee": "400.0",
"lead_plans": [
{
"id": 15,
"lead_id": 62,
"addcosts": "500.0",
"fee": "400.0",
"plan2": "200.0",
"plan3": "300.0",
"probability": "100.0",
"year": 2020
},
{
"id": 18,
"lead_id": 62,
"addcosts": "600.0",
"fee": "500.0",
"plan2": "200.0",
"plan3": "400.0",
"probability": "100.0",
"year": 2020
},
{
"id": 19,
"lead_id": 62,
"addcosts": "500.0",
"fee": "400.0",
"plan2": "200.0",
"plan3": "300.0",
"probability": "100.0",
"year": 2020
}
],
"offers": [
{
"id": 53,
"lead_id": 62,
"addcosts": "400.0",
"addcostsinfo": "test5",
"days": null,
"decision": "test6",
"decisiondate": "2020-05-29",
"fee": "200.0",
"mail": "test",
"offerdate": "2020-05-22",
"paper": "test"
}
]
},
{
"leadplan_plan2": 200,
"leadplan_plan3": 300,
"leadplan_addcosts": 500,
"leadplan_fee": 400
}
],
"Electrical": [
{
"id": 65,
"branch": "Electrical",
"classification": "Einstufungen 2",
"theme": "Sales",
"branch_id": 2,
"classification_id": 1,
"projectno": "12345",
"project_id": 53,
"theme_id": 5,
"projectname": "project12345",
"comment": "test",
"customername": "test123",
"lead1id": 1,
"lead1name": "alpha1",
"lead1percent": "100.0",
"lead2id": 53,
"lead2name": "newuser",
"lead2percent": "200.0",
"lead3id": 51,
"lead3name": "testisbah",
"lead3percent": "300.0",
"leadplan_probability": "1000.0",
"leadplan_plan2": "200.0",
"leadplan_plan3": "300.0",
"leadplan_addcosts": "500.0",
"leadplan_fee": "4000.0",
"lead_plans": [
{
"id": 16,
"lead_id": 65,
"addcosts": "500.0",
"fee": "4000.0",
"plan2": "200.0",
"plan3": "300.0",
"probability": "1000.0",
"year": 2020
},
{
"id": 22,
"lead_id": 65,
"addcosts": "800.0",
"fee": "700.0",
"plan2": "500.0",
"plan3": "600.0",
"probability": "400.0",
"year": 2023
}
],
"offers": [
{
"id": 52,
"lead_id": 65,
"addcosts": "400.0",
"addcostsinfo": "4",
"days": null,
"decision": "4",
"decisiondate": "2020-05-20",
"fee": "400.0",
"mail": "4",
"offerdate": "2020-05-20",
"paper": "4"
},
{
"id": 55,
"lead_id": 65,
"addcosts": "0.0",
"addcostsinfo": "",
"days": null,
"decision": "",
"decisiondate": "2020-05-13",
"fee": "0.0",
"mail": "",
"offerdate": "2020-05-14",
"paper": ""
},
{
"id": 57,
"lead_id": 65,
"addcosts": "0.0",
"addcostsinfo": "",
"days": null,
"decision": "",
"decisiondate": "2020-05-31",
"fee": "0.0",
"mail": "",
"offerdate": "2020-05-09",
"paper": ""
},
{
"id": 56,
"lead_id": 65,
"addcosts": "0.0",
"addcostsinfo": "",
"days": null,
"decision": "",
"decisiondate": "2020-05-30",
"fee": "100.0",
"mail": "",
"offerdate": "2020-05-14",
"paper": ""
},
{
"id": 58,
"lead_id": 65,
"addcosts": "0.0",
"addcostsinfo": "",
"days": null,
"decision": "",
"decisiondate": "2020-05-06",
"fee": "0.0",
"mail": "",
"offerdate": "2020-05-14",
"paper": ""
}
]
},
{
"leadplan_plan2": 200,
"leadplan_plan3": 300,
"leadplan_addcosts": 500,
"leadplan_fee": 4000
}
]
}
And I would like to create an excel or CSV file from it but problem is that my data loads first and excel utility gives error related to null empty.
Is there any reasonable excel npm package from which I can export my data to csv/excel using button click in ReactJs?
If I would be able to export my complete table, that would be good.
The result excel view would be like:

For to mount json

I have in variable bookUnitIdInformacoes this array of objects:
[
{
"id": 5,
"book_id": 33,
"unit": 1,
"sequence": 1,
"description": "UNIT_01_GRAMMAR",
"qt_question": 5,
"status": false,
"user_id": 1,
"created_at": "2019-12-27 08:11:21",
"updated_at": "2019-12-30 14:54:12",
"miniature": null
},
{
"id": 6,
"book_id": 33,
"unit": 1,
"sequence": 2,
"description": "UNIT_01_VOCABULARY",
"qt_question": 5,
"status": false,
"user_id": 1,
"created_at": "2019-12-27 08:11:39",
"updated_at": "2019-12-27 08:11:39",
"miniature": null
},
{
"id": 7,
"book_id": 33,
"unit": 2,
"sequence": 1,
"description": "UNIT_02_GRAMMAR",
"qt_question": 5,
"status": false,
"user_id": 1,
"created_at": "2019-12-27 08:11:46",
"updated_at": "2019-12-27 08:11:46",
"miniature": null
},
{
"id": 8,
"book_id": 39,
"unit": 1,
"sequence": 1,
"description": "UNIT_01_GRAMMAR",
"qt_question": 5,
"status": false,
"user_id": 1,
"created_at": "2019-12-30 11:07:09",
"updated_at": "2019-12-30 15:03:50",
"miniature": null
}
]
I have in the variable idioma this array of objects:
[
{
"id": 13,
"code": "ING-NOT-2019",
"description": "Inglês Noturno 2019",
"start_date": "2019-12-30T03:00:00.000Z",
"end_date": "2019-12-31T03:00:00.000Z",
"period": "Noturno",
"language": "Inglês",
"status": false,
"user_id": 1,
"created_at": "2019-12-30 10:04:47",
"updated_at": "2020-01-05 16:08:00",
"language_substring": "US"
},
{
"id": 14,
"code": "ESP-MAN-2019",
"description": "Espanhol manhã 2019",
"start_date": "2019-12-30T03:00:00.000Z",
"end_date": "2019-12-31T03:00:00.000Z",
"period": "Manhã",
"language": "Espanhol",
"status": false,
"user_id": 1,
"created_at": "2019-12-30 11:06:44",
"updated_at": "2019-12-30 11:06:44",
"language_substring": null
}
]
I need to create a for() that while the column book_id is equal the index+1, insert in idioma[i].quiz the value of the bookUnitIdInformacoes[i] and when the book_id of the bookUnitIdInformacoes array is different, put in the next position of idioma[i]quiz, so i need this json:
[
{
"id": 13,
"code": "ING-NOT-2019",
"description": "Inglês Noturno 2019",
"start_date": "2019-12-30T03:00:00.000Z",
"end_date": "2019-12-31T03:00:00.000Z",
"period": "Noturno",
"language": "Inglês",
"status": false,
"user_id": 1,
"created_at": "2019-12-30 10:04:47",
"updated_at": "2020-01-05 16:08:00",
"language_substring": "US",
"quiz": [
{
"id": 5,
"book_id": 33,
"unit": 1,
"sequence": 1,
"description": "UNIT_01_GRAMMAR",
"qt_question": 5,
"status": false,
"user_id": 1,
"created_at": "2019-12-27 08:11:21",
"updated_at": "2019-12-30 14:54:12",
"miniature": null
},
{
"id": 6,
"book_id": 33,
"unit": 1,
"sequence": 2,
"description": "UNIT_01_VOCABULARY",
"qt_question": 5,
"status": false,
"user_id": 1,
"created_at": "2019-12-27 08:11:39",
"updated_at": "2019-12-27 08:11:39",
"miniature": null
},
{
"id": 7,
"book_id": 33,
"unit": 2,
"sequence": 1,
"description": "UNIT_02_GRAMMAR",
"qt_question": 5,
"status": false,
"user_id": 1,
"created_at": "2019-12-27 08:11:46",
"updated_at": "2019-12-27 08:11:46",
"miniature": null
}
]
},
{
"id": 14,
"code": "ESP-MAN-2019",
"description": "Espanhol manhã 2019",
"start_date": "2019-12-30T03:00:00.000Z",
"end_date": "2019-12-31T03:00:00.000Z",
"period": "Manhã",
"language": "Espanhol",
"status": false,
"user_id": 1,
"created_at": "2019-12-30 11:06:44",
"updated_at": "2019-12-30 11:06:44",
"language_substring": null,
"quiz": [
{
"id": 8,
"book_id": 39,
"unit": 1,
"sequence": 1,
"description": "UNIT_01_GRAMMAR",
"qt_question": 5,
"status": false,
"user_id": 1,
"created_at": "2019-12-30 11:07:09",
"updated_at": "2019-12-30 15:03:50",
"miniature": null
}
]
}
]
I try something like:
for(let i=0;i<quizAbertos.length;i++){
if(i+1 === quizAbertos.length){
break;
}else{
if(bookUnitIdInformacoes[i].book_id === bookUnitIdInformacoes[i+1].book_id){
idioma[i].quiz = bookUnitIdInformacoes[i]
}
}
But i'm getting wrong json..
#Edit:
Actually i'm trying something like:
let book_id
let i_book_id = 0
let i_mudou_book_id = 0;
for(let i=0;i<bookUnitIdInformacoes.length;i++){
if(bookUnitIdInformacoes[i+1] === undefined){
book_id = bookUnitIdInformacoes[bookUnitIdInformacoes.length-1].book_id
}else{
if(bookUnitIdInformacoes[i].book_id === bookUnitIdInformacoes[i+1].book_id){
i_mudou_book_id++
}
}
}
idioma[0].quiz = bookUnitIdInformacoes.splice(0,i_mudou_book_id+1)
idioma[1].quiz = bookUnitIdInformacoes
but this way if i have more than 2 length i will be have problems and if i have only one length i will be too have problems.
First, you can group the bookUnitIdInfomacoes by book_id. This can be done by reducing the array into an object of key => value pairs as book_id => array of books:
{
"33": [
{
"id": 5,
"book_id": 33,
...
},
{
"id": 6,
"book_id": 33,
...
},
{
"id": 7,
"book_id": 33,
...
}
],
"39": [
{
"id": 8,
"book_id": 39,
...
}
]
}
Then, using Object.values will allow us to retrieve only the values of this groupedObj object. This will give us:
[
[
{
"id": 5,
"book_id": 33,
...
},
{
"id": 6,
"book_id": 33,
...
},
{
"id": 7,
"book_id": 33,
...
}
],
[
{
"id": 8,
"book_id": 39,
...
}
]
]
Lastly, we will have to map idiomas and add the corresponding book group into a new property called quizz. For a given idioma, we know its position in idiomas thanks to the second argument of map: i. We can simply do grouped[i] to get the corresponding group of books.
const groupedObj = bookUnitIdInformacoes.reduce((grouped, info) => {
grouped[info.book_id] = grouped[info.book_id] || [];
grouped[info.book_id].push(info);
return grouped;
}, {});
const grouped = Object.values(groupedObj);
const result = idiomas.map((idioma, i) => ({
...idioma,
quizz: grouped[i]
}));
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script>const bookUnitIdInformacoes=[{id:5,book_id:33,unit:1,sequence:1,description:"UNIT_01_GRAMMAR",qt_question:5,status:!1,user_id:1,created_at:"2019-12-27 08:11:21",updated_at:"2019-12-30 14:54:12",miniature:null},{id:6,book_id:33,unit:1,sequence:2,description:"UNIT_01_VOCABULARY",qt_question:5,status:!1,user_id:1,created_at:"2019-12-27 08:11:39",updated_at:"2019-12-27 08:11:39",miniature:null},{id:7,book_id:33,unit:2,sequence:1,description:"UNIT_02_GRAMMAR",qt_question:5,status:!1,user_id:1,created_at:"2019-12-27 08:11:46",updated_at:"2019-12-27 08:11:46",miniature:null},{id:8,book_id:39,unit:1,sequence:1,description:"UNIT_01_GRAMMAR",qt_question:5,status:!1,user_id:1,created_at:"2019-12-30 11:07:09",updated_at:"2019-12-30 15:03:50",miniature:null}],idiomas=[{id:13,code:"ING-NOT-2019",description:"Inglês Noturno 2019",start_date:"2019-12-30T03:00:00.000Z",end_date:"2019-12-31T03:00:00.000Z",period:"Noturno",language:"Inglês",status:!1,user_id:1,created_at:"2019-12-30 10:04:47",updated_at:"2020-01-05 16:08:00",language_substring:"US"},{id:14,code:"ESP-MAN-2019",description:"Espanhol manhã 2019",start_date:"2019-12-30T03:00:00.000Z",end_date:"2019-12-31T03:00:00.000Z",period:"Manhã",language:"Espanhol",status:!1,user_id:1,created_at:"2019-12-30 11:06:44",updated_at:"2019-12-30 11:06:44",language_substring:null}];</script>

Tree massiv get all the links of the elements

I have and object literal that is essentially a tree that does not have a fixed number of levels.
How can I search for a tree for a particular node, and then return this node with connection parameters when it is found in a spectacular javascript manner?
var data = [{
title: 'topNode',
id: 1,
children: [{
title: 'node1',
id: 2,
children: [{
title: 'randomNode_1',
id: 3,
},
{
title: 'node2',
id: 4,
children: [{
title: 'randomNode_2',
id: 5,
children: [{
title: 'node2',
id: 1111,
children: [{
title: 'randomNode_3',
id: 1232,
}]
}]
}]
}
]
}]
}];
tree build   what should be done
tree built from api
serializeGoals: state => type => {
const _goals = JSON.parse(JSON.stringify(state.goals))
return {
title: 'Стратегия',
expand: true,
forst: true,
children: _goals.filter((item) => {
if (item.type !== null && type.some(typeID => typeID === item.type.id)) {
item.shadow = true
} else if (item.type !== null && type.length > 0) {
item.shadow = false
item.type.color = '#ECECEC'
}
item.children = _goals.filter((children) => {
if (children.parent_id === item.id) {
if (children.type !== null && type.some(typeID => typeID === children.type.id)) {
children.shadow = true
} else if (children.type !== null && type.length > 0) {
children.type.color = '#ECECEC'
children.shadow = false
}
return true
}
return false
})
return item.parent_id === null
})
}
}
Get api server JSON array
parent_id - element parent
[{
"id": 5,
"parent_id": null,
"responsible_id": null,
"type_id": 4,
"title": "Тестовая цель - 5",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 4, "title": "Персонал", "color": "#6190e8"}
}, {
"id": 7,
"parent_id": null,
"responsible_id": null,
"type_id": 4,
"title": "Тестовая цель - 7",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 4, "title": "Персонал", "color": "#6190e8"}
}, {
"id": 9,
"parent_id": null,
"responsible_id": null,
"type_id": 4,
"title": "Тестовая цель - 9",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 4, "title": "Персонал", "color": "#6190e8"}
}, {
"id": 11,
"parent_id": null,
"responsible_id": null,
"type_id": 3,
"title": "Тестовая цель - 11",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 3, "title": "Процессы", "color": "#13ce66"}
}, {
"id": 13,
"parent_id": null,
"responsible_id": null,
"type_id": 4,
"title": "Тестовая цель - 13",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 4, "title": "Персонал", "color": "#6190e8"}
}, {
"id": 15,
"parent_id": null,
"responsible_id": null,
"type_id": 2,
"title": "Тестовая цель - 15",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 2, "title": "Клиенты", "color": "#ff4949"}
}, {
"id": 17,
"parent_id": null,
"responsible_id": null,
"type_id": 4,
"title": "Тестовая цель - 17",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 4, "title": "Персонал", "color": "#6190e8"}
}, {
"id": 19,
"parent_id": null,
"responsible_id": null,
"type_id": 4,
"title": "Тестовая цель - 19",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 4, "title": "Персонал", "color": "#6190e8"}
}, {
"id": 20,
"parent_id": 11,
"responsible_id": null,
"type_id": 2,
"title": "Тестовая цель - 20",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 2, "title": "Клиенты", "color": "#ff4949"}
}, {
"id": 21,
"parent_id": null,
"responsible_id": null,
"type_id": 3,
"title": "Тестовая цель - 21",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 3, "title": "Процессы", "color": "#13ce66"}
}, {
"id": 23,
"parent_id": null,
"responsible_id": null,
"type_id": 2,
"title": "Тестовая цель - 23",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 2, "title": "Клиенты", "color": "#ff4949"}
}, {
"id": 25,
"parent_id": null,
"responsible_id": null,
"type_id": 1,
"title": "Тестовая цель - 25",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 1, "title": "Финансы", "color": "#ffc82c"}
}, {
"id": 26,
"parent_id": 15,
"responsible_id": null,
"type_id": 2,
"title": "Тестовая цель - 26",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 2, "title": "Клиенты", "color": "#ff4949"}
}, {
"id": 27,
"parent_id": null,
"responsible_id": null,
"type_id": 1,
"title": "Тестовая цель - 27",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 1, "title": "Финансы", "color": "#ffc82c"}
}, {
"id": 28,
"parent_id": 7,
"responsible_id": null,
"type_id": 2,
"title": "Тестовая цель - 28",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 2, "title": "Клиенты", "color": "#ff4949"}
}, {
"id": 29,
"parent_id": null,
"responsible_id": null,
"type_id": 4,
"title": "Тестовая цель - 29",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 4, "title": "Персонал", "color": "#6190e8"}
}, {
"id": 31,
"parent_id": null,
"responsible_id": null,
"type_id": 2,
"title": "Тестовая цель - 31",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 2, "title": "Клиенты", "color": "#ff4949"}
}, {
"id": 33,
"parent_id": null,
"responsible_id": null,
"type_id": 3,
"title": "Тестовая цель - 33",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 3, "title": "Процессы", "color": "#13ce66"}
}, {
"id": 34,
"parent_id": 31,
"responsible_id": null,
"type_id": 4,
"title": "Тестовая цель - 34",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 4, "title": "Персонал", "color": "#6190e8"}
}, {
"id": 35,
"parent_id": null,
"responsible_id": null,
"type_id": 1,
"title": "Тестовая цель - 35",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 1, "title": "Финансы", "color": "#ffc82c"}
}, {
"id": 36,
"parent_id": 34,
"responsible_id": null,
"type_id": 1,
"title": "Тестовая цель - 36",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 1, "title": "Финансы", "color": "#ffc82c"}
}, {
"id": 37,
"parent_id": null,
"responsible_id": null,
"type_id": 4,
"title": "Тестовая цель - 37",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 4, "title": "Персонал", "color": "#6190e8"}
}, {
"id": 39,
"parent_id": null,
"responsible_id": null,
"type_id": 3,
"title": "Тестовая цель - 39",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 3, "title": "Процессы", "color": "#13ce66"}
}, {
"id": 40,
"parent_id": 34,
"responsible_id": null,
"type_id": 2,
"title": "Тестовая цель - 40",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 2, "title": "Клиенты", "color": "#ff4949"}
}]
I would use a recursive function to iterate through the tree and return the node when the expected one is found (I assumed the title is the search criteria) or return null if none was found.
In example :
var data = [
{
title: 'topNode',
id: 1,
children: [
{
title: 'node1',
id: 2,
children: [
{
title: 'randomNode_1',
id: 3,
},
{
title: 'node2',
id: 4,
children: [
{
title: 'randomNode_2',
id: 5,
children: [
{
title: 'node2',
id: 1111,
children: [
{
title: 'randomNode_3',
id: 1232,
}]
}]
}]
}]
}]
}];
function FindSpecificData(node, titleToFind)
{
let newNode = null;
for (let i = 0; i < node.length; ++i)
{
if (node[i].title == titleToFind)
newNode = node[i];
else if ('children' in node[i])
newNode = FindSpecificData(node[i].children, titleToFind);
if (newNode != null)
return (newNode);
}
return (null);
}
console.log(FindSpecificData(data, 'randomNode_2'));
console.log(FindSpecificData(data, 'randomNode_1'));
console.log(FindSpecificData(data, 'missing node'));
Try this simple method to find out your node
function getNode(node) {
if (node.title === 'randomNode_3') {
return true;
} else if (!node.children && !node.id) {
return false;
} else {
if (node.children) {
for (var i = 0; i < node.children.length; i++) {
getNode(node.children[i])
}
}
}
}
getNode(data[0])

How to get specific data from a list of JSON

I have this JSON
{
"doctors": [
{
"id": 8,
"schedules": [
{
"id": 8,
"totime": "11:17",
"dayId": 2,
"location": "Somajiguda",
"fromtime": "10:17",
"hospitalId": 5,
"day": "Tuesday",
"hospital": "Yashoda"
}
],
"username": "d1",
"degree": "DA(Anaesthesia)",
"email": "1#2.com",
"imagePath": "",
"department": "Bio-Chemistry",
"name": "d1",
"userid": 51,
"gender": "Male",
"mobile": "1234567900"
},
{
"id": 10,
"schedules": [
{
"id": 10,
"totime": "12:35",
"dayId": 2,
"location": "Somajiguda",
"fromtime": "11:35",
"hospitalId": 5,
"day": "Tuesday",
"hospital": "Yashoda"
}
],
"username": "d3",
"degree": "BDS",
"email": "d3#d3.com",
"imagePath": "",
"department": "Bio-Chemistry",
"name": "d3",
"userid": 56,
"gender": "Male",
"mobile": "1234567890"
},
{
"id": 1,
"schedules": [
{
"id": 1,
"totime": "12:55",
"dayId": 1,
"location": "Somajiguda",
"fromtime": "11:55",
"hospitalId": 5,
"day": "Monday",
"hospital": "Yashoda"
}
],
"username": "doctor",
"degree": "BDS",
"email": "",
"imagePath": null,
"department": "Critical Care",
"name": "doctor",
"userid": 4,
"gender": "Male",
"mobile": "1234567890"
},
{
"id": 7,
"schedules": [
{
"id": 7,
"totime": "11:17",
"dayId": 2,
"location": "Somajiguda",
"fromtime": "11:17",
"hospitalId": 5,
"day": "Tuesday",
"hospital": "Yashoda"
}
],
"username": "donald",
"degree": "DA(Anaesthesia)",
"email": "donald#doctor.com",
"imagePath": "",
"department": "Bio-Chemistry",
"name": "donald",
"userid": 47,
"gender": "Male",
"mobile": "1234567989"
},
{
"id": 6,
"schedules": [
{
"id": 6,
"totime": "11:15",
"dayId": 1,
"location": "Somajiguda",
"fromtime": "11:15",
"hospitalId": 5,
"day": "Monday",
"hospital": "Yashoda"
}
],
"username": "john",
"degree": "BDS",
"email": "john#john.com",
"imagePath": null,
"department": "Anesthesiology",
"name": "john",
"userid": 46,
"gender": "Male",
"mobile": "1234567890"
},
{
"id": 5,
"schedules": [
{
"id": 5,
"totime": "13:11",
"dayId": 2,
"location": "Somajiguda",
"fromtime": "12:11",
"hospitalId": 5,
"day": "Tuesday",
"hospital": "Yashoda"
}
],
"username": "sknayak",
"degree": "BDS",
"email": "sknayak#sknayak.com",
"imagePath": "",
"department": "Anesthesiology",
"name": "sknayak",
"userid": 38,
"gender": "Male",
"mobile": "1234567890"
},
{
"id": 2,
"schedules": [
{
"id": 2,
"totime": "16:26",
"dayId": 6,
"location": "Somajiguda",
"fromtime": "15:26",
"hospitalId": 5,
"day": "Saturday",
"hospital": "Yashoda"
}
],
"username": "drsukant",
"degree": "BDS",
"email": "",
"imagePath": null,
"department": "Anesthesiology",
"name": "sukant",
"userid": 9,
"gender": "Male",
"mobile": "1234567890"
}
]
}
In this JSON there is a field id which is unique.I am getting this json via an ajax like this
var test=$.ajax({
type: "GET",
url: projectUrl+"getDoctors",
dataType:"json",
jsonp: true,
async:false
}).responseText;
console.log(test);
As you can see in the JSON there is a field id.For example for id=8 username is d1,id=10,username is d3.I am storing the id in session.So for example if id is 8 then I want only those details(username d1,email 1#2.com.....) whose id is 8.
So how to filter the JSON to a specific value.
You can create a computed for a specific item:
self.doctors = ko.observableArray();
self.d3Doctor = ko.computed(function() {
return ko.utils.arrayFirst(self.doctors(), function(obj) {
return obj.id === 8;
});
});
Now you only have to worry about populating the doctors observableArray:
$.getJSON(projectUrl+"getDoctors", function(response) {
ko.utils.arrayPushAll(yourViewModel.doctors, response.doctors);
});
This allows for the following:
<div data-bind="if: d3Doctor()">
<h3>Doctor with ID 8</h3>
<p>Name: <span data-bind="text: d3Doctor().name"></span></p>
<p>E-mail: <span data-bind="text: d3Doctor().email"></span></p>
<p>Address: <span data-bind="text: d3Doctor().address"></span></p>
...
</div>
You can use each to find it, try this:
$(document).ready(function() {
$.ajax({
type: "GET",
url: projectUrl+"getDoctors",
dataType: "json",
jsonp: true,
async: false
}).done(function(data) {
$.each(data.doctors, function(i, v) {
if (v.id == '8') {
console.log('found', v.username, v.email);
return false;
}
});
});
});
May be this?:
function findById(data, id){
for(var i=0;i<data.length;i++){
if(data[i].id === id) return { username:data[i].username, email:data[i].email};
}
// Or, you can use $.grep like this:
// var foundDoctors = $.grep(data,function(e){return e.id === id;})
// return foundDoctors.length > 0 && foundDoctors[0] || null;
// Or, you can use filter() method from Array (IE 9+)
}
findById(jsondata["doctors"], 8);
Yes. I can answer this.
In my way, I personally prefer to turn all the data into array and itenerate it or manipulate it.
As mention in this question, we already push the data into this format:
doctors.push({id:currPat.id,name:currPat.username});
So, now I can use the array filter function for doctors array:
var result = doctors.filter(function(currentObject) {
return currentObject.id === 8;
});
console.log(result); // {id: 8, name:d1}
Or you can also use the .map() in JQuery, and just make the function to check the data.id and return the pair you want.
And if you would fight for a nano seconds performance. I would guess my method is better than .map()

Categories