Kendo UI HierarchicalDataSource for Treeview with dynamic schema - javascript

I'm trying to display a Kendo treeview thanks to a HierarchicalDataSource.
It's a simple region, country, city hierarchy but the difficulty comes with the fact that we have 3 possible levels of regions and countries can appear at the second or at the third level.
Basically,
- First level of regions contains only other regions
- Second level of regions contains other regions or countries
- Third level of regions contains only countries
Here are my schemas:
var portsSchema = {
schema: {
data: "PortList",
model: {
id: "Code"
}
}
};
var countrySchema = {
schema: {
data: "CountryList",
model: {
id: "Code",
children: portsSchema
}
}
};
var regionCountrySchema = {
schema: {
data: "RegionList",
model: {
id: "id",
children: countrySchema
}
}
};
var regionSchema = {
schema: {
data: "RegionList",
model: {
id: "id",
children: regionCountrySchema
}
}
};
Depending on the fact that the region has countries or not, I would like to specify a specific type of children (regionSchema or regionCountrySchema).
var tvDataSource = new kendo.data.HierarchicalDataSource({
data: regions,
schema: {
model: function (data) {
**how to return the right children schema ?**
}
}
});
Returning { children: regionSchema } or {children: regionCountrySchema } triggers a js kendo error.
Any idea to achieve this ? Thank you.
JSON data sample below.
[
{
"Id": 1,
"Name": "MIDDLE EAST AND RED SEA",
"RegionList": [
{
"Id": 12,
"Name": "MIDDLE EAST",
"RegionList": [
{
"Id": 45,
"Name": "M. EAST",
"RegionList": [
],
"CountryList": [
{
"Id": 12007,
"Code": "AE",
"Name": "UAE",
"PortList": [
{
"Id": 6005,
"Code": "AEJEA",
"Name": "JEBEL ALI"
},
{
"Id": 16014,
"Code": "AEAJM",
"Name": "AJMAN"
},
{
"Id": 16015,
"Code": "AEAUH",
"Name": "ABU DHABI"
},
{
"Id": 15109,
"Code": "AEKLF",
"Name": "KHOR AL FAKKAN"
},
{
"Id": 15001,
"Code": "AERKT",
"Name": "RAS AL KHAIMAH"
},
{
"Id": 16018,
"Code": "AESHJ",
"Name": "SHARJAH"
},
{
"Id": 14863,
"Code": "AEQIW",
"Name": "UMM AL QAIWAIN"
},
{
"Id": 15647,
"Code": "AEFJR",
"Name": "AL - FUJAYRAH"
}
]
},
{
"Id": 12018,
"Code": "OM",
"Name": "OMAN",
"PortList": [
{
"Id": 6011,
"Code": "OMSLL",
"Name": "SALALAH"
},
{
"Id": 16218,
"Code": "OMSOH",
"Name": "SOHAR"
}
]
},
{
"Id": 10069,
"Code": "BH",
"Name": "BAHRAIN",
"PortList": [
{
"Id": 15345,
"Code": "BHKBS",
"Name": "BAHRAIN"
}
]
},
{
"Id": 62292,
"Code": "IQ",
"Name": "IRAQ",
"PortList": [
{
"Id": 15383,
"Code": "IQBSR",
"Name": "BASRA"
},
{
"Id": 14673,
"Code": "IQUQR",
"Name": "UMM QASR PT"
}
]
},
{
"Id": 62291,
"Code": "IR",
"Name": "IRAN, ISLAMIC REPUBLIC OF",
"PortList": [
{
"Id": 15250,
"Code": "IRBKM",
"Name": "BANDAR KHOMEINI"
},
{
"Id": 15249,
"Code": "IRBND",
"Name": "BANDAR ABBAS"
},
{
"Id": 14973,
"Code": "IRBUZ",
"Name": "BUSHEHR"
},
{
"Id": 14671,
"Code": "IRKHO",
"Name": "KHORRAMSHAHR"
}
]
},
{
"Id": 62306,
"Code": "KW",
"Name": "KUWAIT",
"PortList": [
{
"Id": 15810,
"Code": "KWSAA",
"Name": "SHUAIBA"
},
{
"Id": 15811,
"Code": "KWSWK",
"Name": "SHUWAIKH"
}
]
},
{
"Id": 12002,
"Code": "SA",
"Name": "SAUDI ARABIA",
"PortList": [
{
"Id": 15039,
"Code": "SAJUB",
"Name": "JUBAIL"
},
{
"Id": 16147,
"Code": "SADMM",
"Name": "AD DAMMAM"
}
]
},
{
"Id": 62364,
"Code": "QA",
"Name": "QATAR",
"PortList": [
{
"Id": 15739,
"Code": "QADOH",
"Name": "DOHA"
},
{
"Id": 14795,
"Code": "QAMES",
"Name": "MESAIEED"
}
]
}
]
}
],
"CountryList": [
]
},
{
"Id": 30,
"Name": "RED SEA",
"RegionList": [
{
"Id": 65,
"Name": "RED SEA",
"RegionList": [
],
"CountryList": [
]
}
],
"CountryList": [
{
"Id": 12002,
"Code": "SA",
"Name": "SAUDI ARABIA",
"PortList": [
{
"Id": 6003,
"Code": "SAKAC",
"Name": "KING ABDULLAH PORT"
},
{
"Id": 15731,
"Code": "SAJED",
"Name": "JEDDAH"
}
]
},
{
"Id": 10114,
"Code": "DJ",
"Name": "DJIBOUTI",
"PortList": [
{
"Id": 8059,
"Code": "DJJIB",
"Name": "DJIBOUTI"
}
]
},
{
"Id": 10122,
"Code": "ER",
"Name": "ERITREA",
"PortList": [
{
"Id": 15031,
"Code": "ERMSW",
"Name": "MASSAWA"
}
]
},
{
"Id": 62300,
"Code": "JO",
"Name": "JORDAN",
"PortList": [
{
"Id": 14801,
"Code": "JOAQJ",
"Name": "AL \u0027AQABAH"
}
]
},
{
"Id": 50001,
"Code": "SD",
"Name": "sd",
"PortList": [
{
"Id": 15734,
"Code": "SDPZU",
"Name": "PORT SUDAN"
}
]
},
{
"Id": 62425,
"Code": "YE",
"Name": "YEMEN",
"PortList": [
{
"Id": 15302,
"Code": "YEHOD",
"Name": "HODEIDAH"
},
{
"Id": 15304,
"Code": "YEMKX",
"Name": "MUKALLA"
},
{
"Id": 15300,
"Code": "YEADE",
"Name": "ADEN"
}
]
},
{
"Id": 10118,
"Code": "EG",
"Name": "EGYPT",
"PortList": [
{
"Id": 16030,
"Code": "EGSOK",
"Name": "SOKHNA PORT"
}
]
}
]
}
],
"CountryList": [
]
}
]

Related

Extract the parent node name from Tree who has childrens

I want to iterate the tree and need to get the id of all the nodes which has the children in string array. while looping it is just returning me the record but doesn't extract the name of the node.
e.g const result = ['root', 'USER', 'ROLE', 'DASHBOARD', 'BRAND', 'COMPANY'];
{
"id": "root",
"name": "Roles and Permissions",
"children": [
{
"id": "USER",
"name": "USER",
"children": [
{
"id": "1",
"name": "VIEW"
},
{
"id": "2",
"name": "CREATE"
},
{
"id": "3",
"name": "EDIT"
}
]
},
{
"id": "ROLE",
"name": "ROLE",
"children": [
{
"id": "8",
"name": "VIEW"
},
{
"id": "9",
"name": "CREATE"
},
{
"id": "10",
"name": "EDIT"
},
{
"id": "11",
"name": "DELETE"
}
]
},
{
"id": "DASHBOARD",
"name": "DASHBOARD",
"children": [
{
"id": "BRAND",
"name": "BRAND",
"children": [
{
"id": "52",
"name": "VIEW"
},
{
"id": "53",
"name": "CREATE"
},
{
"id": "54",
"name": "EDIT"
},
{
"id": "55",
"name": "DELETE"
}
]
},
{
"id": "COMPANY",
"name": "COMPANY",
"children": [
{
"id": "56",
"name": "VIEW"
},
{
"id": "57",
"name": "CREATE"
},
{
"id": "58",
"name": "EDIT"
},
{
"id": "59",
"name": "DELETE"
}
]
}
]
}
]
}
I tried various looping method to get the list, e.g. but not returning the exact name of the node.
function getParent(nodes) {
if(Array.isArray(nodes.children)) {
return nodes.children.map((node) => getParent(node));
}
return nodes.name;
}
You can store the resp in an array and return that array.
const q = {
"id": "root",
"name": "Roles and Permissions",
"children": [
{
"id": "USER",
"name": "USER",
"children": [
{
"id": "1",
"name": "VIEW"
},
{
"id": "2",
"name": "CREATE"
},
{
"id": "3",
"name": "EDIT"
}
]
},
{
"id": "ROLE",
"name": "ROLE",
"children": [
{
"id": "8",
"name": "VIEW"
},
{
"id": "9",
"name": "CREATE"
},
{
"id": "10",
"name": "EDIT"
},
{
"id": "11",
"name": "DELETE"
}
]
},
{
"id": "DASHBOARD",
"name": "DASHBOARD",
"children": [
{
"id": "BRAND",
"name": "BRAND",
"children": [
{
"id": "52",
"name": "VIEW"
},
{
"id": "53",
"name": "CREATE"
},
{
"id": "54",
"name": "EDIT"
},
{
"id": "55",
"name": "DELETE"
}
]
},
{
"id": "COMPANY",
"name": "COMPANY",
"children": [
{
"id": "56",
"name": "VIEW"
},
{
"id": "57",
"name": "CREATE"
},
{
"id": "58",
"name": "EDIT"
},
{
"id": "59",
"name": "DELETE"
}
]
}
]
}
]
}
let result = []
function r(nodes){
if(Array.isArray(nodes.children)){
result.push(nodes.name);
nodes.children.map((c) => r(c))
return result;
}
return result;
}
console.log(r(q))
You can simply use a recursive function. Here ids is an array. You can initialize it before calling the function. Call this function in your getting IDs method.
const getIdFromNodesWithChild = (node) => {
if (node.children != undefined){
ids.push(node.id)
const children_list = node.children
children_list.forEach( new_child => getIdFromNodesWithChild(new_child))
}}
caller function
const returnIds = (tree) => {
ids = []
getIdFromNodesWithChild(tree)
return (ids)
}
result : ['root', 'USER', 'ROLE', 'DASHBOARD', 'BRAND', 'COMPANY']

Mapping/digging into an array that is nested in an object - JavaScript

This is my first question on stack overflow. I am attempting to map an array that is housed within an object. My question is more regarding the targeting than the actual mapping process itself (I think). The goal of my code is to map an array to this target:
var target = {
"id": 1, //as an int
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters": "all of the batter types as a string",
"ingredients": [],//a copy of all the toppings
"countOfFillings": 0
}
the object in question is:
var bakery = {
"items":
{
"item":
[
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
},
{
"id": "0002",
"type": "donut",
"name": "Raised",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
},
{
"id": "0003",
"type": "donut",
"name": "Old Fashioned",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
},
{
"id": "0004",
"type": "bar",
"name": "Bar",
"ppu": 0.75,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
]
},
"topping":
[
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
],
"fillings":
{
"filling":
[
{ "id": "7001", "name": "None", "addcost": 0 },
{ "id": "7002", "name": "Custard", "addcost": 0.25 },
{ "id": "7003", "name": "Whipped Cream", "addcost": 0.25 }
]
}
},
{
"id": "0005",
"type": "twist",
"name": "Twist",
"ppu": 0.65,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
]
},
"topping":
[
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
]
},
{
"id": "0006",
"type": "filled",
"name": "Filled",
"ppu": 0.75,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
]
},
"topping":
[
{ "id": "5002", "type": "Glazed" },
{ "id": "5007", "type": "Powdered Sugar" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
],
"fillings":
{
"filling":
[
{ "id": "7002", "name": "Custard", "addcost": 0 },
{ "id": "7003", "name": "Whipped Cream", "addcost": 0 },
{ "id": "7004", "name": "Strawberry Jelly", "addcost": 0 },
{ "id": "7005", "name": "Rasberry Jelly", "addcost": 0 }
]
}
}
]
}
}
And this is my attempt at mapping. I'm able to get the array generated but only from the first item in the array as indicated with the [0]. Any feedback or advice would be greatly appreciated!
var exampleTest = bakery.items.item.map(mapCake);
function mapCake (aCake)
{
let newType = `${bakery.items.item[1].type}`
let result = {id: `${bakery.items.item[0].id}`,
type: newType,
name: `${bakery.items.item[0].name}`,
ppu: `${bakery.items.item[0].ppu}`,
batters: [`${bakery.items.item[0].batters.batter}`],
ingredients: `${bakery.items.item[0].topping}`,
countOfFillings: `${bakery.items.item[0].fillings}`.length};
return result
}
Try this:
function mapCake(aCake) {
let newType = `${aCake.type}`;
let result = {
id: `${aCake.id}`,
type: newType,
name: `${aCake.name}`,
ppu: `${aCake.ppu}`,
batters: [`${aCake.batters.batter}`],
ingredients: `${aCake.topping}`,
countOfFillings: `${aCake.fillings}`.length
};
return result;
}
Looks like in your function you're directly indexing a specific bakery item each time.
Your aCake parameter wasn't yet being used, at each iteration, aCake refers to the current item that is being iterated over - so that's what you want to be populating your result values with.

How to aggregate two json data with doing maths

I have two json file one which have contain all team name and code and the second one contain match details and score.i want to make another json which aggregate Total Matches Won-Lost total Goals
json1:https://api.jsonbin.io/b/5d07165d4f234842a566d0b4
json2:https://api.jsonbin.io/b/5d07168c2808a77fb80a2254
i tried to use ... rest operator.
Json 1
{
"name": "English Premier League 2011/12",
"clubs": [
{
"key": "chelsea",
"name": "Chelsea",
"code": "CHE"
},
{
"key": "arsenal",
"name": "Arsenal",
"code": "ARS"
},
{
"key": "tottenham",
"name": "Tottenham Hotspur",
"code": "TOT"
}
]
}
Json2
{
"name": "English Premier League 2011/12",
"rounds": [
{
"name": "Round 1",
"matches": [
{
"date": "2012-01-11",
"team1": {
"key": "tottenham",
"name": "Tottenham Hotspur",
"code": "TOT"
},
"team2": {
"key": "everton",
"name": "Everton",
"code": "EVE"
},
"score1": 2,
"score2": 0
},
{
"date": "2011-08-15",
"team1": {
"key": "mancity",
"name": "Manchester City",
"code": "MCI"
},
"team2": {
"key": "swansea",
"name": "Swansea",
"code": "SWA"
},
"score1": 4,
"score2": 0
},
{
"date": "2011-08-14",
"team1": {
"key": "westbrom",
"name": "West Bromwich Albion",
"code": "WBA"
},
"team2": {
"key": "manutd",
"name": "Manchester United",
"code": "MUN"
},
"score1": 1,
"score2": 2
},
{
"date": "2011-08-14",
"team1": {
"key": "stoke",
"name": "Stoke City",
"code": "STK"
},
"team2": {
"key": "chelsea",
"name": "Chelsea",
"code": "CHE"
},
"score1": 0,
"score2": 0
}
]
}
]
}
Expected JSON Result
"clubs": [
{
"key": "chelsea",
"name": "Chelsea",
"code": "CHE",
"total_matches":38,
"won":"21",
"lost":"15",
"ties":"2",
"total-goals":"33",
"scored-against":"28"
},
{
"key": "arsenal",
"name": "Arsenal",
"code": "ARS",
"total_matches":38,
"won":"21",
"lost":"15",
"ties":"2",
"total-goals":"33",
"scored-against":"28"
}]
Something similar to this might help you need to add extra error checking and few modifications to get the exact result.
let a = {
"name": "English Premier League 2011/12",
"clubs": [{
"key": "chelsea",
"name": "Chelsea",
"code": "CHE"
},
{
"key": "arsenal",
"name": "Arsenal",
"code": "ARS"
},
{
"key": "tottenham",
"name": "Tottenham Hotspur",
"code": "TOT"
}
]
}
let b = {
"name": "English Premier League 2011/12",
"rounds": [{
"name": "Round 1",
"matches": [{
"date": "2012-01-11",
"team1": {
"key": "tottenham",
"name": "Tottenham Hotspur",
"code": "TOT"
},
"team2": {
"key": "everton",
"name": "Everton",
"code": "EVE"
},
"score1": 2,
"score2": 0
},
{
"date": "2011-08-15",
"team1": {
"key": "mancity",
"name": "Manchester City",
"code": "MCI"
},
"team2": {
"key": "swansea",
"name": "Swansea",
"code": "SWA"
},
"score1": 4,
"score2": 0
},
{
"date": "2011-08-14",
"team1": {
"key": "westbrom",
"name": "West Bromwich Albion",
"code": "WBA"
},
"team2": {
"key": "manutd",
"name": "Manchester United",
"code": "MUN"
},
"score1": 1,
"score2": 2
},
{
"date": "2011-08-14",
"team1": {
"key": "stoke",
"name": "Stoke City",
"code": "STK"
},
"team2": {
"key": "chelsea",
"name": "Chelsea",
"code": "CHE"
},
"score1": 0,
"score2": 0
}
]
}]
}
let teamCodes = a.clubs.map(e => e['code']);
console.log("Team codes");
console.log(teamCodes)
let output = {'clubs': []};
teamCodes.map(e=> output.clubs.push({"code": e}))
b.rounds[0].matches.map(ef => {
var total_matches = 0
var won = 0
var lost = 0
var tie = 0
var total_goals = 0
teamCodes.forEach(function(e, index){
var codeIndex = output.clubs.findIndex(function(element, index, array){return element.code ===e})
if(ef.team1.code == e){
output.clubs[codeIndex].code = e
output.clubs[codeIndex].name = ef.team1.name;
output.clubs[codeIndex].key = ef.team1.key;
output.clubs[codeIndex].total_matches = total_matches + 1
output.clubs[codeIndex].total_goals = total_goals + ef.score1
if(ef.score1 > ef.score2) {
output.clubs[codeIndex].won = won + 1
} else if(ef.score1 < ef.score2) {
output.clubs[codeIndex].lost = lost + 1
} else {
output.clubs[codeIndex].tie = tie + 1
}
} else if(ef.team2.code == e) {
output.clubs[codeIndex].code = e
output.clubs[codeIndex].name = ef.team2.name;
output.clubs[codeIndex].key = ef.team2.key;
output.clubs[codeIndex].total_matches = total_matches + 1
output.clubs[codeIndex].total_goals = total_goals + ef.score2
if(ef.score1 > ef.score2) {
output.clubs[codeIndex].won = won + 1
} else if(ef.score1 < ef.score2) {
output.clubs[codeIndex].lost = lost + 1
} else {
output.clubs[codeIndex].tie = tie + 1
}
}
})
})
console.log("Output")
console.dir(output)

Populating select options using jquery fails

I was trying to populate select options from a JSON using jquery. Here is my html form code (with search options) -
<div class="form-group row">
<label for="" class="col-sm-2 form-control-label">Country</label>
<div class="col-sm-10">
<select class="form-control selectpicker" id="country" placeholder="" data-live-search="true">
</select>
</div>
</div>
And here is the code i have write to populate the form with documents and also catch and echo the selection -
(function() {
var url = "dummy.json";
countries = [];
divisions = [];
districts = [];
subdistricts = [];
$.getJSON(url)
.done(function( data ) {
countries.push(data['Country']);
divisions.push(data['Divisions']);
districts.push(data['Districts']);
subdistricts.push(data['Subdistricts']);
$('#country').empty();
for(i=0; i<countries[0].length; i++){
$('#country').append('<option data-tokens="' + countries[0][i]["name"] +'" value="' + i + '">' + countries[0][i]["name"] + '</option>');
};
$('#country').change(function(){
var selected = $( this ).val();
console.log(selected);
});
});
})();
My problem is- the selection form is not populating after running the code. Is there any syntax error in my code ? Or am i approaching it in wrong way ? If anyone want to see the json file, i will post it here.
Here is my JSON file -
{
"Country": [
{
"id": "01",
"name": "China",
"capital": "Beijing",
"divisions": "[01, 02, 03]",
"districts": "[01, 02, 03]"
},
{
"id": "02",
"name": "Bangladesh",
"capital": "Dhaka",
"divisions": "[04,05,06,07,08,09,10,11]",
"Districts": "[04,05,06,07,08,09,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31]"
},
{
"id": "03",
"name": "Singapore",
"Capital": "Singapore City",
"Divisions": "[12,13,14,15,16]",
"Districts": "[32,33,34,35,36]"
}
],
"Divisions": [
{
"id": "01",
"name": "Shengdong",
"districts": [
[
"[01]"
]
]
},
{
"id": "02",
"name": "Anhui",
"districts": [
[
"[02]"
]
]
},
{
"id": "03",
"name": "Fujian",
"districts": [
[
"[03]"
]
]
},
{
"id": "04",
"name": "Barisal",
"districts": "[4,5,6]"
},
{
"id": "05",
"name": "Chittagong",
"Districts": "[07,08,09,10]"
},
{
"id": "06",
"name": "Dhaka",
"Districts": "[11,12]"
},
{
"id": "07",
"name": "Khulna",
"Districts": "[13,14]"
},
{
"id": "08",
"name": "Central Region",
"Districts": [
[
"[15]"
]
]
},
{
"id": "09",
"name": "North Region",
"Districts": [
[
"[16]"
]
]
},
{
"id": "10",
"name": "East Region",
"Districts": [
[
"[17]"
]
]
},
{
"id": "11",
"name": "North-east Region",
"Districts": [
[
"[18]"
]
]
},
{
"id": "12",
"name": "West Region",
"Districts": [
[
"[19]"
]
]
}
],
"Districts": [
{
"id": "1",
"name": "Dongcheng",
"Subdistricts": [
[
"[1]"
]
]
},
{
"id": "2",
"name": "Yaohai",
"Subdistricts": [
[
"[2]"
]
]
},
{
"id": "3",
"name": "Luyang",
"Subdistricts": [
[
"[3]"
]
]
},
{
"id": "4",
"name": "Barisal",
"Subdistricts": [
[
"[4]"
]
]
},
{
"id": "5",
"name": "Barguna",
"Subdistricts": [
[
"[5]"
]
]
},
{
"id": "6",
"name": "Bhola",
"Subdistricts": "[6,7]"
},
{
"id": "7",
"name": "Chittagong",
"Subdistricts": "[8,9,10,11]"
},
{
"id": "8",
"name": "Cox's Bazar",
"Subdistricts": [
[
"[12]"
]
]
},
{
"id": "9",
"name": "Comilla",
"Subdistricts": [
[
"[13]"
]
]
},
{
"id": "10",
"name": "Feni",
"Subdistricts": [
[
"[14]"
]
]
},
{
"id": "11",
"name": "Dhaka",
"Subdistricts": [
[
"[15]"
]
]
},
{
"id": "12",
"name": "Narayanganj",
"Subdistricts": [
[
"[16]"
]
]
},
{
"id": "13",
"name": "Khulna",
"Subdistricts": [
[
"[17]"
]
]
},
{
"id": "14",
"name": "Bagerhat",
"Subdistricts": [
[
"[18]"
]
]
},
{
"id": "15",
"name": "Radin Mas SMC",
"Subdistricts": [
[
"[19]"
]
]
},
{
"id": "16",
"name": "Jalan Besar GRC",
"Subdistricts": [
[
"[20]"
]
]
},
{
"id": "17",
"name": "Mount Batten GRC",
"Subdistricts": [
[
"[21]"
]
]
},
{
"id": "18",
"name": "Marine Parade GRC",
"Subdistricts": [
[
"[22]"
]
]
},
{
"id": "19",
"name": "West Coast GRC",
"Subdistricts": [
[
"[23]"
]
]
}
],
"Subdistricts": [
{
"id": "1",
"name": "Dailang",
"postcodes": "[736200,404000,100000]"
},
{
"id": "2",
"name": "Changchung",
"postcodes": "[864000,504100,905050]"
},
{
"id": "3",
"name": "Chengdu",
"postcodes": "[994000,909100,109050]"
},
{
"id": "4",
"name": "Agailjhara",
"postcodes": "[8240,8241,8242]"
},
{
"id": "5",
"name": "Amtali Upazella",
"postcodes": "[9940,9941,8878]"
},
{
"id": "6",
"name": "Bhola Sadar",
"postcodes": "[7230,7741,7752]"
},
{
"id": "7",
"name": "Daulatkhan",
"postcodes": "[8650,8871,8880]"
},
{
"id": "8",
"name": "Sitakund",
"postcodes": "[4320,4321,4325]"
},
{
"id": "9",
"name": "Satkania",
"postcodes": "[4460,4461,4458]"
},
{
"id": "10",
"name": "Port",
"postcodes": "[4530,4555,4532]"
},
{
"id": "11",
"name": "Dabal Muring",
"postcodes": "[4320,4321,4448]"
},
{
"id": "12",
"name": "Chokaria",
"postcodes": "[5320,5321,5432]"
},
{
"id": "13",
"name": "Daudkandi",
"postcodes": "[6432,6433,6555]"
},
{
"id": "14",
"name": "Feni sadar",
"postcodes": "[3240,3241,3378]"
},
{
"id": "15",
"name": "Dhanmondi",
"postcodes": "[2330,2441,2878]"
},
{
"id": "16",
"name": "Narayanganj Sadar",
"postcodes": "[6444,6543,6657]"
},
{
"id": "17",
"name": "Batiaghat",
"postcodes": "[7780,7781,7778]"
},
{
"id": "18",
"name": "Bagerhat Sadar",
"postcodes": "[7450,7451,7458]"
},
{
"id": "19",
"name": "Changi",
"postcodes": "[736200,404000,555776]"
},
{
"id": "20",
"name": "Quenstown",
"postcodes": "[787899,878788,987789]"
},
{
"id": "21",
"name": "Clementi",
"postcodes": "[989778,976543,975432]"
},
{
"id": "22",
"name": "Tuas",
"postcodes": "[109901,110900,121345]"
},
{
"id": "23",
"name": "East Region",
"postcodes": "[609098,567654,765432]"
}
]
}
Latest EDIT:
I have checked in the console. HTML form with options value is loading perfectly, but for some reason my form is not showing options. Here is my latest code -
for(var i=0; i<countries[0].length; i++){
$('#country').append('<option data-tokens="' + countries[0][i]["name"].toLowerCase() +'" value="' + countries[0][i]["id"] + '">' + countries[0][i]["name"] + '</option>');
};
HTML code after loading in the console -
<select id="country" class="form-control selectpicker" data-live-search="true" placeholder="" tabindex="-98">
<option value="01" data-tokens="china">China</option>
<option value="02" data-tokens="bangladesh">Bangladesh</option>
<option value="03" data-tokens="singapore">Singapore</option>
</select>
Any reason for such phenomenon ?
Change the loop for :
for(var i=0; i<countries[0].length; i++){
$('#country').append('<option data-tokens=' + countries[0][i].name +'value=' + i + '>' + countries[0][i].name + '</option>');
};
Well, it seems my problem was occurring for the selectpicker class i have used. The plugin i have used to generate the search options for the selection has its own criteria for populating options in a select form. Here is the link of their documentation - https://silviomoreto.github.io/bootstrap-select/methods/#selectpickerrefresh
Here is my revised JS code -
(function() {
var url = "dummy.json",
countries = [],
divisions = [],
districts = [],
subdistricts = [],
$.getJSON(url)
.done(function( data ) {
countries.push(data['Country']);
divisions.push(data['Divisions']);
districts.push(data['Districts']);
subdistricts.push(data['Subdistricts']);
var option_string = '';
for(var i=0; i<countries[0].length; i++){
option_string += '<option data-tokens="' + countries[0][i]["name"].toLowerCase() +'" value="' + countries[0][i]["id"] + '">' + countries[0][i]["name"] + '</option>';
}
$('#country').empty().append(option_string).change(function(){
var selected = $(this).val();
console.log(selected);
}).selectpicker('refresh');
});
})();

How to select specific object in JSON

I have JSON Data like below
{
"items":
{
"item":
[
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
},
{
"id": "0002",
"type": "donut",
"name": "Raised",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
}]
}
}
I want to select item object having id 0001.So how can I select or filter only this single item object using javascript or Jquery??
please help me and thanks in advance
Like this:
var item = data.items.item.filter(function(x){
return x.id === '0001';
})[0];

Categories

Resources