Create Functionality in Context Menu of jsTree not working - javascript

New nodes won't be created when 'types' plugin is defined.
Please look at this fiddle.
I'm unable to create new Nodes in the tree.
http://jsfiddle.net/z8L5r9w3/1/
$('#jstree').jstree({
"core" : {
"check_callback" : true,
"data" : [
{ "text" : "Branch 1", "type" : "branch", "children" : [
{ "text" : "leaf 1.1", "type" : "leaf" },
{ "text" : "leaf 1.2", "type" : "leaf" },
{ "text" : "leaf 1.3", "type" : "leaf" }
]
},
{ "text" : "Branch 2", "type" : "branch", "children" : [
{ "text" : "leaf 2.1", "type" : "leaf" },
{ "text" : "leaf 2.2", "type" : "leaf" },
{ "text" : "leaf 2.3", "type" : "leaf" }
]
}
]
},
"types" : {
"#" : {
"valid_children" : ["branch"]
},
"branch" : {
"valid_children" : ["leaf"]
},
"leaf" : {
"valid_children" : []
}
},
"plugins" : ["types", "dnd", "contextmenu"]});

Also, you can override "contextmenu"
"contextmenu":{
"items": function () {
return {
"Create": {
"label": "Create",
"action": function (data) {
var ref = $.jstree.reference(data.reference);
sel = ref.get_selected();
if(!sel.length) { return false; }
sel = sel[0];
type = ref.get_type(sel);
if (type == "#")
type = "branch";
else if (type == "branch")
type = "leaf";
else if (type == "leaf")
type = "";
sel = ref.create_node(sel, {text: "new "+type, type: type});
if(sel) {
ref.edit(sel);
}
}
},
"Rename": {
"label": "Rename",
"action": function (data) {
var inst = $.jstree.reference(data.reference);
obj = inst.get_node(data.reference);
inst.edit(obj);
}
},
"Delete": {
"label": "Delete",
"action": function (data) {
var ref = $.jstree.reference(data.reference),
sel = ref.get_selected();
if(!sel.length) { return false; }
ref.delete_node(sel);
}
}
};
}
},

You have a problem with "types". The "Create" action in the "contextmenu" does not know about the types of "branch" and "leaf" and create new node with "type" : "default".
You can see this:
"types" : {
"#" : {
"valid_children" : ["branch", "default"]
},
"branch" : {
"valid_children" : ["leaf", "default"]
},
"leaf" : {
"valid_children" : []
}
},

Related

Complex mongodb data how to update

I'm trying to update show_seats.showByDate.shows.showSeats.seat_details.values.seat_status
this my code .........................................................................................................................................................
db.seats.updateOne({'show_seats.showByDate.shows.showSeats.seat_details.values._id':"62a9e044ec028e60180fe28a"},{$set:{'show_seats.showByDate.shows.showSeats.seat_details.values.seat_status' : true}})
.........................................................................................................................................................
please say what did i wrong**
{
"_id" : ObjectId("62a43ac2d7213c7233cd1dee"),
"totalShowByDay" : "2",
"totalShowDays" : 4,
"movieId" : ObjectId("62953ba3cb6ae625ec9433e6"),
"screenId" : ObjectId("6293b9638dde2d92658d5513"),
"createdAt" : 1654930114438,
"showId" : ObjectId("62a43ac2d7213c7233cd14ed"),
"show_seats" : [
{
"showByDate" : {
"ShowDate" : "2022-06-11",
"shows" : [
{
"showTime" : "2022-06-11T10:00",
"showSeats" : [
[
{
"category" : "CLASSIC",
"seat_details" : [
{
"key" : "A",
"values" : [
{
"_id" : ObjectId("62a43ac2d7213c7233cd14ee"),
"seat_number" : "1",
"tag_name" : "A",
"seat_status" : false,
"user_id" : false,
"price" : "140",
"seats_category" : "CLASSIC",
"show_time" : "2022-06-11T10:00"
},
,
{
"_id" : ObjectId("62a43ac2d7213c7233cd14ef"),
"seat_number" : "2",
"tag_name" : "A",
"seat_status" : false,
"user_id" : false,
"price" : "140",
"seats_category" : "CLASSIC",
"show_time" : "2022-06-11T10:00"
},
{
"_id" : ObjectId("62a43ac2d7213c7233cd14f0"),
"seat_number" : "3",
"tag_name" : "A",
"seat_status" : false,
"user_id" : false,
"price" : "140",
"seats_category" : "CLASSIC",
"show_time" : "2022-06-11T10:00",,
{
"_id" : ObjectId("62a43ac2d7213c7233cd14ef"),
"seat_number" : "2",
"tag_name" : "A",
"seat_status" : false,
"user_id" : false,
"price" : "140",
"seats_category" : "CLASSIC",
"show_time" : "2022-06-11T10:00"
},
{
"_id" : ObjectId("62a43ac2d7213c7233cd14f0"),
"seat_number" : "3",
"tag_name" : "A",
"seat_status" : false,
"user_id" : false,
"price" : "140",
"seats_category" : "CLASSIC",
"show_time" : "2022-06-11T10:00"
}
this is what i ended up doing, I need best solution
await db.getDb().collection(coll.seat).aggregate([
{
'$unwind': {
'path': '$show_seats'
}
}, {
'$unwind': {
'path': '$show_seats.showByDate.shows'
}
}, {
'$unwind': {
'path': '$show_seats.showByDate.shows.showSeats'
}
}, {
'$unwind': {
'path': '$show_seats.showByDate.shows.showSeats'
}
}, {
'$unwind': {
'path': '$show_seats.showByDate.shows.showSeats.seat_details'
}
}, {
'$unwind': {
'path': '$show_seats.showByDate.shows.showSeats.seat_details.values'
}
}, {
'$match': {
'show_seats.showByDate.shows.showSeats.seat_details.values._id': ObjectId("62a43ac2d7213c7233cd14ee")
}
}, {
$addFields: { "show_seats.showByDate.shows.showSeats.seat_details.values.seat_status": true }
}
])

Display data in consistent format for array of documents

I have a collection personemail with array of documents
{ "Name" : "A", "Email" : [ { "EmailAddress" : "a#home.com", "EmailType" : "Home" }, { "EmailAddress" : "a#work.com", "EmailType" : "Work" } ] }
{ "Name" : "B", "Email" : [ { "EmailAddress" : "b#work.com", "EmailType" : "Work" } ] }
{ "Name" : "C" }
I have to display data in below format, ie if we a person is not having home / work address , it should be displayed as "No data" if home or work email is not available preferably in same order (Home email first , Work email second)
{ "Name" : "A", "Email" : [ { "EmailAddress" : "a#home.com", "EmailType" : "Home" }, { "EmailAddress" : "a#work.com", "EmailType" : "Work" } ] }
{ "Name" : "B", "Email" : [ { "EmailAddress" : "No Data", "EmailType" : "Home" }, { "EmailAddress" : "b#work.com", "EmailType" : "Work" } ] }
{ "Name" : "C", "Email" : [ { "EmailAddress" : "No Data", "EmailType" : "Home" }, { "EmailAddress" : "No Data", "EmailType" : "Work" } ] }
I thought of implementing this with $unwind or $switch function . Suggestions please
It's possible:
db.collection.aggregate([
{ "$project": {
"Name": 1,
"Email": {
"$map": {
"input": ["Home", "Work"],
"as": "m",
"in": {
"$ifNull": [
{ "$arrayElemAt": [
{ "$filter": {
"input": "$Email",
"as": "e",
"cond": { "$eq": [ "$$e.EmailType", "$$m" ] }
}},
0
]},
{ "EmailAddress": "No Data", "EmailType": "$$m" }
]
}
}
}
}}
])
Which produces:
{
"_id" : ObjectId("591e7d66cb1a9433dab779cc"),
"Name" : "A",
"Email" : [
{
"EmailAddress" : "a#home.com",
"EmailType" : "Home"
},
{
"EmailAddress" : "a#work.com",
"EmailType" : "Work"
}
]
}
{
"_id" : ObjectId("591e7d66cb1a9433dab779cd"),
"Name" : "B",
"Email" : [
{
"EmailAddress" : "No Data",
"EmailType" : "Home"
},
{
"EmailAddress" : "b#work.com",
"EmailType" : "Work"
}
]
}
{
"_id" : ObjectId("591e7d66cb1a9433dab779ce"),
"Name" : "C",
"Email" : [
{
"EmailAddress" : "No Data",
"EmailType" : "Home"
},
{
"EmailAddress" : "No Data",
"EmailType" : "Work"
}
]
}
But personally I'd do that transformation in client code, since it's less obtuse. As a quick shell example:
db.collection.find().forEach(doc => {
doc.Email = ["Home", "Work"].map( m => {
if (!doc.hasOwnProperty('Email'))
doc.Email = [];
var val = doc.Email.filter(e => e.EmailType === m)[0];
return (val == null) ? { "EmailAddress": "No Data", "EmailType": m }
: val;
});
printjson(doc);
})
Basically though you use your "uniform" array of "Home" and "Work" as a source to $map, then lookup the elements in the documents current Email array. anything that returned a null on the lookup is swapped with the default data.

Javascript menu recursive function bugs

//current jsfiddle
http://jsfiddle.net/0ht35rpb/45/
I am trying to loop through a json navigation tree - so that when a person goes to a particular page, it finds its alternative language counter-part.
//JSON
{
"langs" : [
{
"lang" : "de",
"lines" : {
"menu" : [
{
"title" : "Anleitung",
"link" : "/de/anleitung"
},
{
"title" : "Funktionen",
"link" : "/de/funktionen"
},
{
"title" : "Dienstleistungen",
"link" : "/de/dienstleistungen",
"children" : [
{
"title" : "Geistiges Eigentum",
"link" : "/de/dienstleistungen/geistiges-eigentum"
},
{
"title" : "Compliance",
"link" : "/de/dienstleistungen/compliance"
},
{
"title" : "Investment- und Beteiligungsrecht",
"link" : "/de/dienstleistungen/beteiligungsrecht"
},
{
"title" : "Mergers & Acquisitions",
"link" : "/de/dienstleistungen/mergers-and-acquisitions"
},
{
"title" : "Immobilienrecht",
"link" : "/de/dienstleistungen/immobilienrecht"
},
{
"title" : "Internet- und Datenschutzrecht",
"link" : "/de/dienstleistungen/internetrecht"
},
{
"title" : "Gesellschaftsrecht",
"link" : "/de/dienstleistungen/gesellschaftsrecht"
},
{
"title" : "Handelsrecht",
"link" : "/de/dienstleistungen/handelsrecht"
},
{
"title" : "Arbeitsrecht",
"link" : "/de/dienstleistungen/arbeitsrecht"
},
{
"title" : "Bankrecht",
"link" : "/de/dienstleistungen/bankrecht"
},
{
"title" : "Vertragsrecht",
"link" : "/de/dienstleistungen/vertragsrecht"
},
{
"title" : "Wettbewerbsrecht",
"link" : "/de/dienstleistungen/wettbewerbsrecht"
}
]
},
{
"title" : "Beliebte Projekte",
"link" : "/de/beliebte-projekte",
"children" : [
{
"title" : "Compliance",
"link" : "/de/beliebte-projekte/compliance",
"children" : [
{
"title" : "Haftungsrisiken für Geschäftsführern",
"link" : "/de/beliebte-projekte/compliance/haftungsrisken-geschaeftsfuehrern"
},
{
"title" : "Compliance-Prüfung KMU",
"link" : "/de/beliebte-projekte/compliance/compliance-pruefung-kmu"
}
]
}
]
}
],
"sign_in" : "Login"
}
},
{
"lang" : "en",
"lines" : {
"menu" : [
{
"title" : "How it works",
"link" : "/en/how-it-works"
},
{
"title" : "Features",
"link" : "/en/features"
},
{
"title" : "Services",
"link" : "/en/services",
"children" : [
{
"title" : "Intellectual property",
"link" : "/en/services/intellectual-property"
},
{
"title" : "Compliance",
"link" : "/en/services/compliance"
},
{
"title" : "Investment law",
"link" : "/en/services/investment-law"
},
{
"title" : "Mergers & Acquisitions",
"link" : "/en/services/mergers-and-acquisitions"
},
{
"title" : "Real estate law",
"link" : "/en/services/real-estate-law"
},
{
"title" : "Internet law and data privacy",
"link" : "/en/services/internet-law"
},
{
"title" : "Company law",
"link" : "/en/services/company-law"
},
{
"title" : "Trade law",
"link" : "/en/services/trade-law"
},
{
"title" : "Labour law",
"link" : "/en/services/labour-law"
},
{
"title" : "Bank law",
"link" : "/en/services/bank-law"
},
{
"title" : "Contract law",
"link" : "/en/services/contract-law"
},
{
"title" : "Competition law",
"link" : "/en/services/competition-law"
}
]
},
{
"title" : "Popular Projects",
"link" : "/en/popular-projects",
"children" : [
{
"title" : "Compliance",
"link" : "/en/popular-projects/compliance",
"children" : [
{
"title" : "Haf eng",
"link" : "/en/popular-projects/compliance/haf-eng"
},
{
"title" : "Compliance eng",
"link" : "/en/popular-projects/compliance/compliance-eng"
}
]
}
]
}
],
"sign_in" : "Sign in"
}
}
]
}
my js functions
so in this case
imagine
CURRENTLNG as en
CURRENTURL as /en/services
in fetchFooterUrls () - I want to return an array with ["/en/services", "/de/dienstleistungen"]
this code falls down in trying to get the 3rd level navigation counter parts
["/en/popular-projects/compliance/compliance-eng", "/de/beliebte-projekte/compliance/compliance-pruefung-kmu"]
getUrl (pairUrl, currentLng, enMenu, deMenu, obj) {
for (let k in obj) {
if (!obj.hasOwnProperty(k)) continue
if (obj[k].link === pairUrl) {
if (currentLng === 'de') {
return enMenu[k].link // get en link equivlant
} else {
return deMenu[k].link // get de link equivlant
}
} else {
if (obj[k].hasOwnProperty('children') && obj[k].children.length > 0) continue
this.getUrl(pairUrl, currentLng, enMenu[k].children, deMenu[k].children, obj[k].children)
}
}
}
//
getLanguagePair (currentLng, pairUrl) {
// 'find url in json tree'
var enMenu = linkTreeObject.langs[1].lines.menu
var deMenu = linkTreeObject.langs[0].lines.menu
let obj = {}
// find position in tree
if (currentLng === 'de') {
obj = deMenu
} else {
obj = enMenu
}
return this.getUrl(pairUrl, currentLng, enMenu, deMenu, obj)
}
fetchFooterUrls () {
let deUrl = ''
let enUrl = ''
if (CURRENTLNG === 'de') {
deUrl = CURRENTURL
enUrl = this.getLanguagePair(CURRENTLNG, this.props.location.pathname)
} else {
enUrl = CURRENTURL
deUrl = this.getLanguagePair(CURRENTLNG, this.props.location.pathname)
}
return [enUrl, deUrl]
}
//tried to make this snippet - any moderators here to resolve?
var linkTreeObject ={
"langs" : [
{
"lang" : "de",
"lines" : {
"menu" : [
{
"title" : "Anleitung",
"link" : "/de/anleitung"
},
{
"title" : "Funktionen",
"link" : "/de/funktionen"
},
{
"title" : "Dienstleistungen",
"link" : "/de/dienstleistungen",
"children" : [
{
"title" : "Geistiges Eigentum",
"link" : "/de/dienstleistungen/geistiges-eigentum"
},
{
"title" : "Compliance",
"link" : "/de/dienstleistungen/compliance"
},
{
"title" : "Investment- und Beteiligungsrecht",
"link" : "/de/dienstleistungen/beteiligungsrecht"
},
{
"title" : "Mergers & Acquisitions",
"link" : "/de/dienstleistungen/mergers-and-acquisitions"
},
{
"title" : "Immobilienrecht",
"link" : "/de/dienstleistungen/immobilienrecht"
},
{
"title" : "Internet- und Datenschutzrecht",
"link" : "/de/dienstleistungen/internetrecht"
},
{
"title" : "Gesellschaftsrecht",
"link" : "/de/dienstleistungen/gesellschaftsrecht"
},
{
"title" : "Handelsrecht",
"link" : "/de/dienstleistungen/handelsrecht"
},
{
"title" : "Arbeitsrecht",
"link" : "/de/dienstleistungen/arbeitsrecht"
},
{
"title" : "Bankrecht",
"link" : "/de/dienstleistungen/bankrecht"
},
{
"title" : "Vertragsrecht",
"link" : "/de/dienstleistungen/vertragsrecht"
},
{
"title" : "Wettbewerbsrecht",
"link" : "/de/dienstleistungen/wettbewerbsrecht"
}
]
},
{
"title" : "Beliebte Projekte",
"link" : "/de/beliebte-projekte",
"children" : [
{
"title" : "Compliance",
"link" : "/de/beliebte-projekte/compliance",
"children" : [
{
"title" : "Haftungsrisiken für Geschäftsführern",
"link" : "/de/beliebte-projekte/compliance/haftungsrisken-geschaeftsfuehrern"
},
{
"title" : "Compliance-Prüfung KMU",
"link" : "/de/beliebte-projekte/compliance/compliance-pruefung-kmu"
}
]
}
]
}
],
"sign_in" : "Login"
}
},
{
"lang" : "en",
"lines" : {
"menu" : [
{
"title" : "How it works",
"link" : "/en/how-it-works"
},
{
"title" : "Features",
"link" : "/en/features"
},
{
"title" : "Services",
"link" : "/en/services",
"children" : [
{
"title" : "Intellectual property",
"link" : "/en/services/intellectual-property"
},
{
"title" : "Compliance",
"link" : "/en/services/compliance"
},
{
"title" : "Investment law",
"link" : "/en/services/investment-law"
},
{
"title" : "Mergers & Acquisitions",
"link" : "/en/services/mergers-and-acquisitions"
},
{
"title" : "Real estate law",
"link" : "/en/services/real-estate-law"
},
{
"title" : "Internet law and data privacy",
"link" : "/en/services/internet-law"
},
{
"title" : "Company law",
"link" : "/en/services/company-law"
},
{
"title" : "Trade law",
"link" : "/en/services/trade-law"
},
{
"title" : "Labour law",
"link" : "/en/services/labour-law"
},
{
"title" : "Bank law",
"link" : "/en/services/bank-law"
},
{
"title" : "Contract law",
"link" : "/en/services/contract-law"
},
{
"title" : "Competition law",
"link" : "/en/services/competition-law"
}
]
},
{
"title" : "Popular Projects",
"link" : "/en/popular-projects",
"children" : [
{
"title" : "Compliance",
"link" : "/en/popular-projects/compliance",
"children" : [
{
"title" : "Haf eng",
"link" : "/en/popular-projects/compliance/haf-eng"
},
{
"title" : "Compliance eng",
"link" : "/en/popular-projects/compliance/compliance-eng"
}
]
}
]
}
],
"sign_in" : "Sign in"
}
}
]
};
getUrl (pairUrl, currentLng, enMenu, deMenu, obj) {
for (let k in obj) {
if (!obj.hasOwnProperty(k)) continue
if (obj[k].link === pairUrl) {
if (currentLng === 'de') {
return enMenu[k].link // get en link equivlant
} else {
return deMenu[k].link // get de link equivlant
}
} else {
if (obj[k].hasOwnProperty('children') && obj[k].children.length > 0) continue
this.getUrl(pairUrl, currentLng, enMenu[k].children, deMenu[k].children, obj[k].children)
}
}
}
//
getLanguagePair (currentLng, pairUrl) {
// 'find url in json tree'
var enMenu = linkTreeObject.langs[1].lines.menu
var deMenu = linkTreeObject.langs[0].lines.menu
let obj = {}
// find position in tree
if (currentLng === 'de') {
obj = deMenu
} else {
obj = enMenu
}
return this.getUrl(pairUrl, currentLng, enMenu, deMenu, obj)
}
console.log(getLanguagePair("en", "/en/how-it-works"))
Updated the jsfiddle. You had errors related to the recursive function call in the else part.
http://jsfiddle.net/gaganshera/0ht35rpb/51/
Changed it to
if (!obj[k].hasOwnProperty('children') || obj[k].children.length <= 0) continue;
var ret = getUrl(pairUrl, currentLng, enMenu[k].children, deMenu[k].children, obj[k].children);
if(typeof ret != 'undefined') return ret;
var linkTreeObject = {
"langs": [{
"lang": "de",
"lines": {
"menu": [{
"title": "Anleitung",
"link": "/de/anleitung"
}, {
"title": "Funktionen",
"link": "/de/funktionen"
}, {
"title": "Dienstleistungen",
"link": "/de/dienstleistungen",
"children": [{
"title": "Geistiges Eigentum",
"link": "/de/dienstleistungen/geistiges-eigentum"
}, {
"title": "Compliance",
"link": "/de/dienstleistungen/compliance"
}, {
"title": "Investment- und Beteiligungsrecht",
"link": "/de/dienstleistungen/beteiligungsrecht"
}, {
"title": "Mergers & Acquisitions",
"link": "/de/dienstleistungen/mergers-and-acquisitions"
}, {
"title": "Immobilienrecht",
"link": "/de/dienstleistungen/immobilienrecht"
}, {
"title": "Internet- und Datenschutzrecht",
"link": "/de/dienstleistungen/internetrecht"
}, {
"title": "Gesellschaftsrecht",
"link": "/de/dienstleistungen/gesellschaftsrecht"
}, {
"title": "Handelsrecht",
"link": "/de/dienstleistungen/handelsrecht"
}, {
"title": "Arbeitsrecht",
"link": "/de/dienstleistungen/arbeitsrecht"
}, {
"title": "Bankrecht",
"link": "/de/dienstleistungen/bankrecht"
}, {
"title": "Vertragsrecht",
"link": "/de/dienstleistungen/vertragsrecht"
}, {
"title": "Wettbewerbsrecht",
"link": "/de/dienstleistungen/wettbewerbsrecht"
}]
}, {
"title": "Beliebte Projekte",
"link": "/de/beliebte-projekte",
"children": [{
"title": "Compliance",
"link": "/de/beliebte-projekte/compliance",
"children": [{
"title": "Haftungsrisiken für Geschäftsführern",
"link": "/de/beliebte-projekte/compliance/haftungsrisken-geschaeftsfuehrern"
}, {
"title": "Compliance-Prüfung KMU",
"link": "/de/beliebte-projekte/compliance/compliance-pruefung-kmu"
}]
}]
}],
"sign_in": "Login"
}
}, {
"lang": "en",
"lines": {
"menu": [{
"title": "How it works",
"link": "/en/how-it-works"
}, {
"title": "Features",
"link": "/en/features"
}, {
"title": "Services",
"link": "/en/services",
"children": [{
"title": "Intellectual property",
"link": "/en/services/intellectual-property"
}, {
"title": "Compliance",
"link": "/en/services/compliance"
}, {
"title": "Investment law",
"link": "/en/services/investment-law"
}, {
"title": "Mergers & Acquisitions",
"link": "/en/services/mergers-and-acquisitions"
}, {
"title": "Real estate law",
"link": "/en/services/real-estate-law"
}, {
"title": "Internet law and data privacy",
"link": "/en/services/internet-law"
}, {
"title": "Company law",
"link": "/en/services/company-law"
}, {
"title": "Trade law",
"link": "/en/services/trade-law"
}, {
"title": "Labour law",
"link": "/en/services/labour-law"
}, {
"title": "Bank law",
"link": "/en/services/bank-law"
}, {
"title": "Contract law",
"link": "/en/services/contract-law"
}, {
"title": "Competition law",
"link": "/en/services/competition-law"
}]
}, {
"title": "Popular Projects",
"link": "/en/popular-projects",
"children": [{
"title": "Compliance",
"link": "/en/popular-projects/compliance",
"children": [{
"title": "Haf eng",
"link": "/en/popular-projects/compliance/haf-eng"
}, {
"title": "Compliance eng",
"link": "/en/popular-projects/compliance/compliance-eng"
}]
}]
}],
"sign_in": "Sign in"
}
}]
};
function getUrl(pairUrl, currentLng, enMenu, deMenu, obj) {
for (let k in obj) {
if (!obj.hasOwnProperty(k)) continue
if (obj[k].link === pairUrl) {
if (currentLng === 'de') {
return enMenu[k].link // get en link equivlant
} else {
return deMenu[k].link // get de link equivlant
}
} else {
if (!obj[k].hasOwnProperty('children') || obj[k].children.length <= 0) continue;
var ret = getUrl(pairUrl, currentLng, enMenu[k].children, deMenu[k].children, obj[k].children);
if(typeof ret != 'undefined') return ret;
}
}
}
function getLanguagePair(currentLng, pairUrl) {
// 'find url in json tree'
var enMenu = linkTreeObject.langs[1].lines.menu
var deMenu = linkTreeObject.langs[0].lines.menu
let obj = {}
// find position in tree
if (currentLng === 'de') {
obj = deMenu
} else {
obj = enMenu
}
return getUrl(pairUrl, currentLng, enMenu, deMenu, obj)
}
//works
console.log(getLanguagePair("en", "/en/how-it-works"))
console.log(getLanguagePair("en", "/en/popular-projects"))
console.log(getLanguagePair("de", "/de/anleitung"))
console.log(getLanguagePair("de", "/de/beliebte-projekte"))
//fail
console.log(getLanguagePair("en", "/en/services/compliance"))
console.log(getLanguagePair("en", "/en/popular-projects/compliance"))
console.log(getLanguagePair("en", "/en/popular-projects/compliance/compliance-eng"))
there is a problem in your recursive function. If you don't match the url at the first function call, you recursively call the function again but you don't return it.
function get_10_recursive(number){
if(number>=10) return 10;
else return get_10_recursive(number++);
}
In this example, if the number is smaller than 10, the function is recursively called until it encounter a return statement, after this, it retrace the stack and returns you the correct result. If you remove the return statement in the third line the code is executed as well but it returns the result only of the first call, which is undefined.
The problem in your code is that, if you place a return inside the for loop, the loop gets interrupted and you won't check the next strings, so you have to store the results of the function call in a temporary variable and return it only if it's truthy (aka it's not undefined).
Your getUrl function becomes like this:
function getUrl(pairUrl, currentLng, enMenu, deMenu, obj) {
for (var k in obj) {
if (obj[k].link === pairUrl) {
if (currentLng === 'de') {
return enMenu[k].link; // get en link equivlant
} else {
return deMenu[k].link; // get de link equivlant
}
} else {
if (obj[k].hasOwnProperty('children')){
var tmp = getUrl(pairUrl, currentLng, enMenu[k].children, deMenu[k].children, obj[k].children);
if(tmp) return tmp; // check if it found the match successfully
}
}
}
}
PS: I remvoed the if (!obj.hasOwnProperty(k)) continue because it was useless

underscore - locating node based in a value

This is my 1st time using underscore...I've this simple json...
"categories" : [
{
"tag" : "cat1",
"active" : true,
"order" : 10,
"title" : {
"en" : "Category 1",
"pt" : "Categoria 1"
},
"children" : [
{
"tag" : "cat11",
"active" : true,
"order" : 10,
"title" : {
"en" : "Category 1.1",
"pt" : "Categoria 1.1"
}
},
{
"tag" : "cat12",
"active" : true,
"order" : 20,
"title" : {
"en" : "Category 1.2",
"pt" : "Categoria 1.2"
}
}
]
},
{
"tag" : "cat2",
"active" : true,
"order" : 10,
"title" : {
"en" : "Category 2",
"pt" : "Categoria 2"
},
"children" : [
{
"tag" : "cat21",
"active" : true,
"order" : 10,
"title" : {
"en" : "Category 2.1",
"pt" : "Categoria 2.1"
}
},
{
"tag" : "cat22",
"active" : true,
"order" : 20,
"title" : {
"en" : "Category 2.2",
"pt" : "Categoria 2.2"
}
}
]
},
{
"tag" : "cat3",
"active" : true,
"order" : 10,
"title" : {
"en" : "Category 3",
"pt" : "Categoria 3"
},
"children" : [
{
"tag" : "cat31",
"active" : true,
"order" : 10,
"title" : {
"en" : "Category 3.1",
"pt" : "Categoria 3.1"
}
},
{
"tag" : "cat32",
"active" : true,
"order" : 20,
"title" : {
"en" : "Category 3.2",
"pt" : "Categoria 3.2"
}
}
]
},
{
"tag" : "cat4",
"active" : true,
"order" : 10,
"title" : {
"en" : "Category 4",
"pt" : "Categoria 4"
},
"children" : [
{
"tag" : "cat41",
"active" : true,
"order" : 10,
"title" : {
"en" : "Category 4.1",
"pt" : "Categoria 4.1"
}
},
{
"tag" : "cat42",
"active" : true,
"order" : 20,
"title" : {
"en" : "Category 4.2",
"pt" : "Categoria 4.2"
}
}
]
}
]
you can see I've the TAG key in several places. I need to get the entire tree based in a criteria for tag. I was using, find, filter, where and findWhere and all the time I got the same results:
var find = _.find($rootScope.webshop.categories, {tag: 'cat1'});
this works !
but if I try...
var find = _.find($rootScope.webshop.categories, {tag: 'cat11'});
No results :( Even using _.where or ._filter or ._findWhere. - The results always will be the same.
Can someone help a beginner in Underscore with something that's probably simple ?!
ty !
_.find does not recurse, you will have to build your own solution. Something like this:
_.findIn = function() {
var args = Array.prototype.slice.call(arguments, 0);
var childrenProp = args[0];
var result = _.find.apply(_, args.slice(1));
if (result !== void(8)) return result;
var arr = args[1];
for (var i = 0, l = arr.length; i < l; i++) {
args[1] = arr[i][childrenProp];
var result = _.findIn.apply(_, args);
if (result !== void(8)) return result;
}
return void(8);
}
_.findIn('children', categories, {tag: 'cat11'})
categories = [
{
"tag" : "cat1",
"active" : true,
"order" : 10,
"title" : {
"en" : "Category 1",
"pt" : "Categoria 1"
},
"children" : [
{
"tag" : "cat11",
"active" : true,
"order" : 10,
"title" : {
"en" : "Category 1.1",
"pt" : "Categoria 1.1"
}
},
{
"tag" : "cat12",
"active" : true,
"order" : 20,
"title" : {
"en" : "Category 1.2",
"pt" : "Categoria 1.2"
}
}
]
},
{
"tag" : "cat2",
"active" : true,
"order" : 10,
"title" : {
"en" : "Category 2",
"pt" : "Categoria 2"
},
"children" : [
{
"tag" : "cat21",
"active" : true,
"order" : 10,
"title" : {
"en" : "Category 2.1",
"pt" : "Categoria 2.1"
}
},
{
"tag" : "cat22",
"active" : true,
"order" : 20,
"title" : {
"en" : "Category 2.2",
"pt" : "Categoria 2.2"
}
}
]
},
{
"tag" : "cat3",
"active" : true,
"order" : 10,
"title" : {
"en" : "Category 3",
"pt" : "Categoria 3"
},
"children" : [
{
"tag" : "cat31",
"active" : true,
"order" : 10,
"title" : {
"en" : "Category 3.1",
"pt" : "Categoria 3.1"
}
},
{
"tag" : "cat32",
"active" : true,
"order" : 20,
"title" : {
"en" : "Category 3.2",
"pt" : "Categoria 3.2"
}
}
]
},
{
"tag" : "cat4",
"active" : true,
"order" : 10,
"title" : {
"en" : "Category 4",
"pt" : "Categoria 4"
},
"children" : [
{
"tag" : "cat41",
"active" : true,
"order" : 10,
"title" : {
"en" : "Category 4.1",
"pt" : "Categoria 4.1"
}
},
{
"tag" : "cat42",
"active" : true,
"order" : 20,
"title" : {
"en" : "Category 4.2",
"pt" : "Categoria 4.2"
}
}
]
}
]
_.findIn = function() {
var args = Array.prototype.slice.call(arguments, 0);
var childrenProp = args[0];
var result = _.find.apply(_, args.slice(1));
if (result !== void(8)) return result;
var arr = args[1];
for (var i = 0, l = arr.length; i < l; i++) {
args[1] = arr[i][childrenProp];
var result = _.findIn.apply(_, args);
if (result !== void(8)) return result;
}
return void(8);
}
document.write(JSON.stringify(_.findIn('children', categories, {tag: 'cat11'})));
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>

SAPUI5 create JSON for TreeTable / empty rows

I want to create a SAPUI TreeTable from a JSON request, currently my output looks like this (as you can see, every node contains an empty row -> I do not know where this is coming from and I do not want to have these empty rows):
My Table definition:
//Create an instance of the table control
var oTreeTable = new sap.ui.table.TreeTable({
columns: [
new sap.ui.table.Column({
label : new sap.ui.commons.Label({
text : "",
}),
template :
new sap.ui.commons.TextView({
text : "{Title}",
textAlign : sap.ui.core.TextAlign.Begin,
}),
}),
//new sap.ui.table.Column({label: "Mon01", template: "Mon01"}),
//new sap.ui.table.Column({label: "Mon02", template: "Mon02"}),
//new sap.ui.table.Column({label: "Mon03", template: "Mon03"}),
//new sap.ui.table.Column({label: "Mon04", template: "Mon04"}),
],
selectionMode: sap.ui.table.SelectionMode.None,
enableColumnReordering: false,
expandFirstLevel: false,
toggleOpenState: function(oEvent) {
}
});
My getJSON and convert flat structure to parent/child structure (thanks to yaku)
$.getJSON(sServiceUrl, function (data) {
// flatten to object with string keys that can be easily referenced later
var flat = {};
for (var i = 0; i < data.d.results.length; i++) {
var key = 'id' + data.d.results[i].ID;
flat[key] = data.d.results[i];
}
// add child container array to each node
for (var i in flat) {
flat[i].children = []; // add children container
}
// populate the child container arrays
for (var i in flat) {
var parentkey = 'id' + flat[i].ParentId;
if (flat[parentkey]) {
flat[parentkey].children.push(flat[i]);
}
}
// find the root nodes (no parent found) and create the hierarchy tree from them
var root = [];
for (var i in flat) {
var parentkey = 'id' + flat[i].ParentId;
if (!flat[parentkey]) {
root.push(flat[i]);
}
}
// here it is!
// console.log(root);
// to access the JSON via "/root" in bindRows(), could this be a problem??
var data = {
root : root,
};
console.log(data);
var oTreeModel = new sap.ui.model.json.JSONModel();
oTreeModel.setData(data);
oTreeTable.setModel(oTreeModel);
oTreeTable.bindRows({
path : '/root',
});
My Result JSON (a part of it): where I can not find why there are empty rows shown ?? Anybody knows something?
Thanks!
Edit: this is my complete JSON result (var root) (BEFORE I move it to var data = { root : root, }; which is bound to the tree table via bindRows(/root).. )
{
"d" : {
"results" : [
{
"__metadata" : {
"id" : "http://url/EntitySet('00000001')",
"uri" : "http://url/EntitySet('00000001')",
"type" : " NAMESPACE_SRV.Entity"
},
"Mon04" : "",
"Mon03" : "",
"Mon02" : "09/2014",
"Mon01" : "08/2014",
"Title" : "Parent 1",
"ID" : "00000001",
"ParentId" : "",
"ChildId" : "",
},
{
"__metadata" : {
"id" : "http://url/EntitySet('00000002')",
"uri" : "http://url/EntitySet('00000002')",
"type" : "NAMESPACE_SRV.Entity"
},
"Mon04" : "",
"Mon03" : "",
"Mon02" : "1560",
"Mon01" : "1550",
"Title" : "Parent 2",
"ID" : "00000002",
"ParentId" : "",
"ChildId" : "",
},
{
"__metadata" : {
"id" : "http://url/EntitySet('00000003')",
"uri" : "http://url/EntitySet('00000003')",
"type" : "NAMESPACE_SRV.Entity"
},
"Mon04" : "",
"Mon03" : "",
"Mon02" : "1860",
"Mon01" : "1750",
"Title" : "Child 1",
"ID" : "00000003",
"ParentId" : "00000002",
"ChildId" : "00000001",
},
{
"__metadata" : {
"id" : "http://url/EntitySet('00000004')",
"uri" : "http://url/EntitySet('00000004')",
"type" : "NAMESPACE_SRV.Entity"
},
"Mon04" : "",
"Mon03" : "",
"Mon02" : "1860",
"Mon01" : "1750",
"Title" : "Child 1_1",
"ID" : "00000004",
"ParentId" : "00000003",
"ChildId" : "00000001",
},
{
"__metadata" : {
"id" : "http://url/EntitySet('00000005')",
"uri" : "http://url/EntitySet('00000005')",
"type" : "NAMESPACE_SRV.Entity"
},
"Mon04" : "",
"Mon03" : "",
"Mon02" : "2060",
"Mon01" : "1950",
"Title" : "Child 2",
"ID" : "00000005",
"ParentId" : "00000002",
"ChildId" : "00000001",
},
{
"__metadata" : {
"id" : "http://url/EntitySet('00000006')",
"uri" : "http://url/EntitySet('00000006')",
"type" : "NAMESPACE_SRV.Entity"
},
"Mon04" : "",
"Mon03" : "",
"Mon02" : "2060",
"Mon01" : "1950",
"Title" : "Child 3",
"ID" : "00000006",
"ParentId" : "00000002",
"ChildId" : "00000001",
}
]
}
}
During trying to remove the bullet points I found that they are included in HTML, but I dont know why. If I remove this via dev-tools, the bullet point is gone...
which comes from CSS icon class...
.sapUiTableTreeIconLeaf {
background-image: url(ico12_leaf.gif);
}
solved it via
.sapUiTableTreeIconLeaf {
background-image: none !important;
}
just get rid of the __metadata, set flat[key].__metadata = "" , i guess TreeTable renderer must take it for another child.
// flatten to object with string keys that can be easily referenced later
var flat = {};
for (var i = 0; i < data.d.results.length; i++) {
var key = 'id' + data.d.results[i].ID;
flat[key] = data.d.results[i];
flat[key].__metadata = "";
}
Updated Code Snippet:
sap.ui.jsview("test.view", {
getControllerName: function() {
return "test.controller";
},
createContent: function(oController) {
var oTreeTable = new sap.ui.table.TreeTable({
columns: [
new sap.ui.table.Column({
label: "Title",
template: "Title"
}),
new sap.ui.table.Column({
label: "Mon01",
template: "Mon01"
}),
new sap.ui.table.Column({
label: "Mon02",
template: "Mon02"
}),
new sap.ui.table.Column({
label: "Mon03",
template: "Mon03"
}),
new sap.ui.table.Column({
label: "Mon04",
template: "Mon04"
}),
],
selectionMode: sap.ui.table.SelectionMode.None,
enableColumnReordering: false,
expandFirstLevel: false,
toggleOpenState: function(oEvent) {
}
});
var data = {
"d": {
"results": [{
"__metadata": {
"id": "http://url/EntitySet('00000001')",
"uri": "http://url/EntitySet('00000001')",
"type": " NAMESPACE_SRV.Entity"
},
"Mon04": "",
"Mon03": "",
"Mon02": "09/2014",
"Mon01": "08/2014",
"Title": "Parent 1",
"ID": "00000001",
"ParentId": "",
"ChildId": "",
}, {
"__metadata": {
"id": "http://url/EntitySet('00000002')",
"uri": "http://url/EntitySet('00000002')",
"type": "NAMESPACE_SRV.Entity"
},
"Mon04": "",
"Mon03": "",
"Mon02": "1560",
"Mon01": "1550",
"Title": "Parent 2",
"ID": "00000002",
"ParentId": "",
"ChildId": "",
}, {
"__metadata": {
"id": "http://url/EntitySet('00000003')",
"uri": "http://url/EntitySet('00000003')",
"type": "NAMESPACE_SRV.Entity"
},
"Mon04": "",
"Mon03": "",
"Mon02": "1860",
"Mon01": "1750",
"Title": "Child 1",
"ID": "00000003",
"ParentId": "00000002",
"ChildId": "00000001",
}, {
"__metadata": {
"id": "http://url/EntitySet('00000004')",
"uri": "http://url/EntitySet('00000004')",
"type": "NAMESPACE_SRV.Entity"
},
"Mon04": "",
"Mon03": "",
"Mon02": "1860",
"Mon01": "1750",
"Title": "Child 1_1",
"ID": "00000004",
"ParentId": "00000003",
"ChildId": "00000001",
}, {
"__metadata": {
"id": "http://url/EntitySet('00000005')",
"uri": "http://url/EntitySet('00000005')",
"type": "NAMESPACE_SRV.Entity"
},
"Mon04": "",
"Mon03": "",
"Mon02": "2060",
"Mon01": "1950",
"Title": "Child 2",
"ID": "00000005",
"ParentId": "00000002",
"ChildId": "00000001",
}, {
"__metadata": {
"id": "http://url/EntitySet('00000006')",
"uri": "http://url/EntitySet('00000006')",
"type": "NAMESPACE_SRV.Entity"
},
"Mon04": "",
"Mon03": "",
"Mon02": "2060",
"Mon01": "1950",
"Title": "Child 3",
"ID": "00000006",
"ParentId": "00000002",
"ChildId": "00000001",
}]
}
};
var flat = {};
for (var i = 0; i < data.d.results.length; i++) {
var key = 'id' + data.d.results[i].ID;
flat[key] = data.d.results[i];
flat[key].__metadata = "";
}
// add child container array to each node
for (var i in flat) {
flat[i].children = []; // add children container
}
// populate the child container arrays
for (var i in flat) {
var parentkey = 'id' + flat[i].ParentId;
if (flat[parentkey]) {
flat[parentkey].children.push(flat[i]);
}
}
// find the root nodes (no parent found) and create the hierarchy tree from them
var root = [];
for (var i in flat) {
var parentkey = 'id' + flat[i].ParentId;
if (!flat[parentkey]) {
root.push(flat[i]);
}
}
// here it is!
// console.log(root);
// to access the JSON via "/root" in bindRows(), could this be a problem??
var data = {
root: root,
};
console.log(data);
var oTreeModel = new sap.ui.model.json.JSONModel();
oTreeModel.setData(data);
oTreeTable.setModel(oTreeModel);
oTreeTable.bindRows({
path: '/root',
});
return oTreeTable;
},
});
sap.ui.controller("test.controller", {
onInit: function() {
}
});
sap.ui.view({
type: sap.ui.core.mvc.ViewType.JS,
viewName: "test.view"
})
.placeAt("uiArea");
<script id='sap-ui-bootstrap' type='text/javascript' src='https://sapui5.hana.ondemand.com/resources/sap-ui-core.js' data-sap-ui-libs="sap.m,sap.ui.commons,sap.ui.table,sap.viz" data-sap-ui-theme="sap_bluecrystal"></script>
<body class="sapUiBody">
<div id="uiArea"></div>
</body>

Categories

Resources