jqTree - creating tree data from json - javascript

I'm trying to display a tree using jqTree - http://mbraak.github.com/jqTree
I need help with creating the tree data from JSON.
My JSON data looks like this:
{
"d" : {
"results": [
{
"Title": "Committee A",
"ReportsToId": null,
"Rank": 1,
"Id": 5
},
{
"Title": "Committee B",
"ReportsToId": 5,
"Rank": 2,
"Id": 7
},
{
"Title": "Committee C",
"ReportsToId": 7,
"Rank": 3,
"Id": 13
},
{
"Title": "Committee D",
"ReportsToId": 13,
"Rank": 4,
"Id": 1
},
{
"Title": "Committee E",
"ReportsToId": 13,
"Rank": 4,
"Id": 3
}
]
}
}
I want to end up with this:
var treeData = [
{
label: 'Committee A',
children: [
{
label: 'Committee B',
children: [
{
label: 'Committee C',
children: [
{ label: 'Committee D' },
{ label: 'Committee E' }
]
}]
}
]
}
];

Here's a solution adapted from http://www.jqwidgets.com/populating-jquery-tree-with-json-data/:
var jqTreeData = function (data) {
var source = [];
var items = [];
// build hierarchical source.
for (i = 0; i < data.length; i++) {
var item = data[i];
var title = item["Title"];
var reportsToId = item["ReportsToId"];
var id = item["Id"];
if (items[reportsToId]) {
var item =
{
label: title
};
if (!items[reportsToId].children) {
items[reportsToId].children = [];
}
items[reportsToId].children[items[reportsToId].children.length] = item;
items[id] = item;
}
else {
items[id] =
{
label: title
};
source[0] = items[id];
}
}
return source;
}

Related

Find the parent of the searched value using javascript

I have a JSON data in the following format which needs to be filtered based on a specific value :
[
{
"id": 0,
"name": "ROOT-0",
"childs": [
{
"id": 1,
"name": "ROOT-1",
"childs": [
{
"id": 11,
"name": "ROOT-11",
},
{
"id": 12,
"name": "ROOT-12",
},
]
},
{
"id": 2,
"name": "ROOT-2",
"childs": [
{
"id": 21,
"name": "ROOT-21",
},
{
"id": 22,
"name": "ROOT-22",
},
]
},
{
"id": 3,
"name": "ROOT-3",
"childs": [
{
"id": 31,
"name": "ROOT-31",
},
{
"id": 32,
"name": "ROOT-32",
},
]
}
]
}]
The scenario is that I need to get ROOT-1 as final result if I look for ROOT-11/ROOT-12.
I have tried filtering with this following code
var res = data[0].filter(function f(o) {
if (o.name.includes("ROOT-11")) return o;
})
But I am not able to get a grip on the logic. Is there a way to achieve my desired output
You could use find()...
var result = data[0].childs.find(x => {
return x.childs.find(y => {
return y.name === name;
});
}).name;
Or you could write a function...
function findParentName(name, data) {
return data[0].childs.find(x => {
return x.childs.find(y => {
return y.name === name;
});
}).name;
}
var result = findParentName('ROOT-11', data);
console.log(result);
Doing this will give you the best performance result as find() will return as soon as it finds a match, and not iterate through each remaining loop like forEach() or map()
If you're using ES6 you can say...
const result = data[0].childs.find(x => x.childs.find(y => y.name === 'ROOT-11')).name;
You can grab the item using a few filters and a find, to get the result you are looking for:
let items = [{
"id": 0,
"name": "ROOT-0",
"childs": [{
"id": 1,
"name": "ROOT-1",
"childs": [{
"id": 11,
"name": "ROOT-11",
},
{
"id": 12,
"name": "ROOT-12",
},
]
},
{
"id": 2,
"name": "ROOT-2",
"childs": [{
"id": 21,
"name": "ROOT-21",
},
{
"id": 22,
"name": "ROOT-22",
},
]
},
{
"id": 3,
"name": "ROOT-3",
"childs": [{
"id": 31,
"name": "ROOT-31",
},
{
"id": 32,
"name": "ROOT-32",
},
]
}
]
}]
function find(name) {
let result
items.filter(item =>
result = item.childs.find(item2 =>
item2.childs.filter(i => i.name == name).length > 0
)
)
return result.name || ''
}
console.log(find('ROOT-11'))
console.log(find('ROOT-22'))
console.log(find('ROOT-32'))
You could, for an arbitrary count nested children, use a recusion approach by iterating the actual level and if not found check the children with the actual name.
If the wanted name is found, the parent's name is handed over through all nested calls and returned.
function getParent(array, search, parent) {
return array.some(o => o.name === search || o.children && (parent = getParent(o.children, search, o.name)))
&& parent;
}
var data = [{ id: 0, name: "ROOT-0", children: [{ id: 1, name: "ROOT-1", children: [{ id: 11, name: "ROOT-11" }, { id: 12, name: "ROOT-12" }] }, { id: 2, name: "ROOT-2", children: [{ id: 21, name: "ROOT-21" }, { id: 22, name: "ROOT-22" }] }, { id: 3, name: "ROOT-3", children: [{ id: 31, name: "ROOT-31" }, { id: 32, name: "ROOT-32" }] }] }]
console.log(getParent(data, 'ROOT-0')); // undefined no parent found
console.log(getParent(data, 'ROOT-1')); // ROOT-0
console.log(getParent(data, 'ROOT-11')); // ROOT-1
console.log(getParent(data, 'ROOT-31')); // ROOT-3
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sorting JSON alphabetically by first letter

I have a JSON like this:
[
{
"id": 1,
"slug": "abakan",
"name": "Абакан"
},
{
"id": 4,
"slug": "almetevsk",
"name": "Альметьевск"
},
{
"id": 10,
"slug": "astrahan",
"name": "Астрахань"
},
{
"id": 11,
"slug": "barnaul",
"name": "Барнаул"
},
...
]
And getting this by this method:
public function getCities()
{
$cities = City::mainCities()->get(['id', 'slug', 'name']);
return response()->json($cities);
}
How can i sort this list alphabetically and with their letters. For example:
"A": [
{
"id": 1,
"slug": "abakan",
"name": "Абакан"
},
{
"id": 4,
"slug": "almetevsk",
"name": "Альметьевск"
}
],
"B": [
{
"id": 11,
"slug": "barnaul",
"name": "Барнаул"
},
...
]
and so on...
I have Laravel on the backend and VueJS on front.
My solution:
var cities = [
{ id: 1, slug: "abakan", name: "Абакан" },
{ id: 4, slug: "almetevsk", name: "Альметьевск" },
{ id: 11, slug: "barnaul", name: "Барнаул" },
{ id: 10, slug: "astrahan", name: "Астрахань" }
];
cities.sort(function(a, b) {
return a.slug[0].localeCompare(b.slug[0]);
});
var newCities = {};
for (var i = 0; i < cities.length; i++) {
var c = cities[i].slug[0].toUpperCase();
if (newCities[c] && newCities[c].length >= 0)
newCities[c].push(cities[i]);
else {
newCities[c] = [];
newCities[c].push(cities[i]);
}
}
console.log(newCities);
This works for me:
var items = [
{
"id": 11,
"slug": "barnaul",
"name": "Барнаул"
},
{
"id": 1,
"slug": "abakan",
"name": "Абакан"
},
{
"id": 4,
"slug": "almetevsk",
"name": "Альметьевск"
},
{
"id": 10,
"slug": "astrahan",
"name": "Астрахань"
}
];
var sortedItems = items.sort((a, b) => a.slug.localeCompare(b.slug));
var results = {};
for (var i = 0; i < 26; i++) {
var char = String.fromCharCode(97 + i);
var bigChar = char.toUpperCase();
results[bigChar] = [];
for (var s = 0; s < sortedItems.length; s++) {
if (sortedItems[s].slug.startsWith(char)) {
results[bigChar].push(sortedItems[s]);
}
}
}
console.log(results)

Javascript object sum values of same property key

I Have the following object and I want to sum the values of the same ingredients name, like: tomato: 5, chicken:5, rice: 1, peas: 1, i have this code but is not making the sum, instead is showing all the objects
var data3 = {
"menus": [{
"recipe": "chicken with rice",
"ingredients": [{
"name": "tomato",
"value": 2
}, {
"name": "chicken",
"value": 3
}, {
"name": "rice",
"value": 1
}]
}, {
"recipe": "Garden rice",
"ingredients": [{
"name": "tomato",
"value": 3
}, {
"name": "chicken",
"value": 2
}, {
"name": "peas",
"value": 1
}]
}]
};
var ingredients;
for (var i = 0; i < 10; i++) {
ingredients = data3.menus[i].ingredients;
var temp = {};
var obj = null;
for (var j = 0; j < ingredients.length; j++) {
obj = ingredients[j];
if (!temp[obj.name]) {
temp[obj.name] = obj;
} else {
temp[obj.name].value += obj.value;
}
}
var result = [];
for (var prop in temp)
result.push(temp[prop]);
console.log(result);
};
I will appreciate your help, thanks!
You could use a hash table with the name of the ingredient and use a default value of zero if a property does not exist. Then add the value.
var data3 = { menus: [{ recipe: "chicken with rice", ingredients: [{ name: "tomato", value: 2 }, { name: "chicken", value: 3 }, { name: "rice", value: 1 }] }, { recipe: "Garden rice", ingredients: [{ name: "tomato", value: 3 }, { name: "chicken", value: 2 }, { name: "peas", value: 1 }] }] },
ingredients = Object.create(null);
data3.menus.forEach(function (a) {
a.ingredients.forEach(function (b) {
ingredients[b.name] = (ingredients[b.name] || 0) + b.value;
});
});
console.log(ingredients);
Your implementation is correct, just you were re-initializing temp again and again. So you just need to take temp out of your for loop.
var data3 = {
"menus": [{
"recipe": "chicken with rice",
"ingredients": [{
"name": "tomato",
"value": 2
}, {
"name": "chicken",
"value": 3
}, {
"name": "rice",
"value": 1
}]
}, {
"recipe": "Garden rice",
"ingredients": [{
"name": "tomato",
"value": 3
}, {
"name": "chicken",
"value": 2
}, {
"name": "peas",
"value": 1
}]
}]
};
var ingredients;
var temp = {};
for (var i = 0; i < data3.menus.length; i++) {
ingredients = data3.menus[i].ingredients;
var obj = null;
for (var j = 0; j < ingredients.length; j++) {
obj = ingredients[j];
if (!temp[obj.name]) {
temp[obj.name] = obj;
} else {
temp[obj.name].value += obj.value;
}
}
};
var result = [];
for (var prop in temp)
result.push(temp[prop]);
console.log(result);
You can create a function that will traverse all ingredients and if ingredient.name has given name, then add ingredient.value to your result. Here is ES2015 solution with arrow functions:
const sumIngredients = (menus, name) => {
let result = 0;
menus.forEach(meal => {
meal.ingredients.forEach(ingredient => {
if (ingredient.name === name) {
result += ingredient.value;
}
})
})
return result;
}
The use it:
sumIngredients(data3.menus, 'chicken'); //5
sumIngredients(data3.menus, 'tomato'); //5
sumIngredients(data3.menus, 'rice'); //1
sumIngredients(data3.menus, 'peas'); //1
Working example: https://jsfiddle.net/sc8wrupk/

Javascript get data totals into list

I have this data:
{
"id": "123",
"name": "name here",
"thsub": {
"637": {
"id": "637",
"name": "Sub 1",
"stats": {
"items": 5,
},
"ons": null
},
"638": {
"id": "638",
"name": "Sub 2",
"stats": {
"items": 10,
},
"ons": null
}
},
"ph": 10,
}
Here's is the code:
mydata = [mydata];
var chList=[];
var thList=[];
var thCount=[];
for (var i = 0; i < mydata.length; i++) {
var obj = mydata[i];
var cl = obj.name;
if (obj.thsub != null) {
chList.push(cl);
}
if(obj.thsub) {
if (i < 10) {
var nme = Object.keys(obj.thsub).map( function(key){
var item = obj.thsub[key];
return item.name;
});
thCount.push(numberofitems);
thList = thList.concat(nme);
thCount = thCount.concat(Array(nme.length).fill(nme.length));
}
}
}
My problem is in the thCount ... what I need to do is to count each "items" on obj.thsub.638 or other ...stats.items and put the totals into thCount like I've got in thList.
So the desired result woule be 5 and 10 in other words: [5, 10] in this case.
thCount would be [5, 10]
How can I do this?
you should access the json objects using key value, index is for arrays. below code just does the thcount for you
var data = {
"id": "123",
"name": "name here",
"thsub": {
"637": {
"id": "637",
"name": "Sub 1",
"stats": {
"items": 5,
},
"ons": null
},
"638": {
"id": "638",
"name": "Sub 2",
"stats": {
"items": 10,
},
"ons": null
}
},
"ph": 10,
};
var thCount = [];
for(key in data.thsub ){
if(data.thsub[key].stats){
thCount.push(data.thsub[key].stats.items);
}
}
console.log(thCount);
Object.values gives you the list of values of a given object and then you can map your result in an array. in ES5:
var arr = Object.values(mydata.thsub).map(function(item) {
return item.stats.items
});
in ES6:
const list = Object.values(mydata.thsub).map(item => item.stats.items);
You could use an iterative recursive approach for getting the wanted values.
function getValues(object, key) {
function iter(o) {
if (key in o) {
result.push(o[key]);
}
Object.keys(o).forEach(function (k) {
if (o[k] && typeof o[k] === 'object') {
iter(o[k]);
}
});
}
var result = [];
iter(object);
return result;
}
var data = { id: "123", name: "name here", thsub: { 637: { id: "637", name: "Sub 1", stats: { items: 5, }, ons: null }, 638: { id: "638", name: "Sub 2", stats: { items: 10, }, ons: null } }, ph: 10, };
console.log(getValues(data, 'items'));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Making one to many relation array in JavaScript

I have two arrays of objects:
var a = [{
"id": 1,
"name": "q"
},
{
"id": 2,
"name": "l"
}]
and another is
var b = [{
"id": 3,
"sub": 1,
"name": "ni"
},
{
"id": 4,
"sub": 2,
"name": "bh"
}]
Here sub is the id in a
I need to have a new array which will look like this:
var c = [
{
"id":1,
"name":"q",
"map":[
{
"id":3,
"name":"ni"
}
]
},
{
"id":2,
"name":"l",
"map":[
{
"id":4,
"name":"bh"
}
]
}
]
How can I do that in JavaScript?
I am using underscore in my project.
In plain Javascript you could use Array#map, Array#forEach and a hash table.
var a = [{ "id": 1, "name": "q" }, { "id": 2, "name": "l" }],
b = [{ "id": 3, "sub": 1, "name": "ni" }, { "id": 4, "sub": 2, "name": "bh" }],
hash = Object.create(null),
result = a.map(function (a, i) {
hash[a.id] = { id: a.id, name: a.name };
return hash[a.id];
}, hash);
b.forEach(function (a) {
hash[a.sub].map = hash[a.sub].map || [];
hash[a.sub].map.push({ id: a.id, name: a.name });
}, hash);
console.log(result);
ES6
var a = [{ "id": 1, "name": "q" }, { "id": 2, "name": "l" }],
b = [{ "id": 3, "sub": 1, "name": "ni" }, { "id": 4, "sub": 2, "name": "bh" }],
hash = Object.create(null),
result = a.map((hash => a => hash[a.id] = { id: a.id, name: a.name, map: [] })(hash));
b.forEach((hash => a => hash[a.sub].map.push({ id: a.id, name: a.name }))(hash));
console.log(result);
You can do it with the help of map function and then use the find function to search the data from the other array.
var b = [{
"id": 3,
"sub": 1,
"name": "ni"
}, {
"id": 4,
"sub": 2,
"name": "bh"
}];
var a = [{
"id": 1,
"name": "q"
}, {
"id": 2,
"name": "l"
}];
var final = _.map(b, function(d) {
return {
id: d.name,
name: d.name,
map: _.find(a, function(adata) {
return adata.id == d.sub; //use underscore find to get the relevant data from array a
})
}
});
console.log(final);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

Categories

Resources