How can I populate Kendo UI grid with nested JSON.
I mean my JSON is like
var myJson:
[{"oneType":[
{"id":1,"name":"John Doe"},
{"id":2,"name":"Don Joeh"}
]},
{"othertype":"working"},
{"otherstuff":"xyz"}]
}];
and I want Kendo UI Grid with columns as Id, Name, OtherType and OtherStuff.
Thanks in advance.!
For complex JSON structures, you might use schema.parse
var grid = $("#grid").kendoGrid({
dataSource : {
data : [
{
"oneType": [
{"id": 1, "name": "John Doe"},
{"id": 2, "name": "Don Joeh"}
]
},
{"othertype": "working"},
{"otherstuff": "xyz"}
],
pageSize: 10,
schema : {
parse : function(d) {
for (var i = 0; i < d.length; i++) {
if (d[i].oneType) {
return d[i].oneType;
}
}
return [];
}
}
}
}).data("kendoGrid");
If you slightly change your JSON to:
{
"oneType" : [
{"id": 1, "name": "John Doe"},
{"id": 2, "name": "Don Joeh"}
],
"othertype" : "working",
"otherstuff": "xyz"
}
then you can use:
var grid = $("#grid").kendoGrid({
dataSource: {
data : {
"oneType" : [
{"id": 1, "name": "John Doe"},
{"id": 2, "name": "Don Joeh"}
],
"othertype" : "working",
"otherstuff": "xyz"
},
pageSize: 10,
schema : {
data: "oneType"
}
}
}).data("kendoGrid");
I just wanted to submit another answer based on OnaBai's.
http://jsfiddle.net/L6LwW/17/
The HTML:
<script id="message-template" type="text/x-kendo-template">
#for (var i = 0; i
< ddl.length; i++) {# <li><span>#=ddl[i].value#</li>
#}#
</script>
<div id="grid"></div>
The JS:
var grid = $("#grid").kendoGrid({
dataSource: {
data: [
[{
"id": 1,
"name": "John Doe",
"ddl": [{
"key": 1,
"value": "hello"
}, {
"key": 1,
"value": "hello"
}]
}, {
"id": 2,
"name": "Don Joeh",
"ddl": [{
"key": 1,
"value": "hello"
}, {
"key": 1,
"value": "hello"
}]
}]
],
pageSize: 10,
schema: {
parse: function(d) {
for (var i = 0; i < d.length; i++) {
if (d[i]) {
return d[i];
}
}
return [];
}
}
},
columns: [{
field: "id",
title: "ID"
}, {
field: "name",
title: "Name"
}, {
field: "ddl",
title: "DDL",
width: "180px",
template: kendo.template($("#message-template").html())
} //template: "#=ddl.value#" }
]
}).data("kendoGrid");
Related
Hi I am getting data from API but I want my data in different format so that I can pass later into a function. I want to change the names of keys into a different one becasuse I have created a chart and it only draws if I send it data in certain way
This is what I am getting from API
data = {
"status": "success",
"from": "DB",
"indice": "KSE100",
"data": [
{
"stock_sector_name": "Tc",
"sector_score": "0828",
"stocks": [
{
"stock_symbol": "TRG",
"stock_score": 44
},
{
"stock_symbol": "SYS",
"stock_score": 33
}
]
},
{
"stock_sector_name": "OIL",
"sector_score": "0828",
"stocks": [
{
"stock_symbol": "FFS",
"stock_score": 44
},
{
"stock_symbol": "SMS",
"stock_score": 33
}
]
},
]
}
But I want my data to look like this like this
data = {
"name": "KSE100",
"children": [
{
"name": "A",
'points': -9,
"children": [
{
"stock_title": "A",
"value": 12,
},
{
"stock_title": "B",
"value": 4,
},
]
},
{
"name": "B",
'points': 20,
"children": [
{
"stock_title": "A",
"value": 12,
},
{
"name": "B",
"value": 4,
},
]
},
]
}
Like I want to replace
stock_sector_name = name
sector_score = value
stocks = children
stock_symbol = name
stock_score = value
I have been trying this for so much time but sill could not figured it out
function convert(d){
return {
name : d.indice,
children : d.data.map(y=>{
return {
name : y.stock_sector_name,
points : y.sector_score,
children : y.stocks.map(z=>{
return {
stock_title: z.stock_symbol,
value : z.stock_score
}
})
}
})
}
}
You can do something like this
const data = {
"status": "success",
"from": "DB",
"indice": "KSE100",
"data": [{
"stock_sector_name": "Tc",
"sector_score": "0828",
"stocks": [{
"stock_symbol": "TRG",
"stock_score": 44
},
{
"stock_symbol": "SYS",
"stock_score": 33
}
]
},
{
"stock_sector_name": "OIL",
"sector_score": "0828",
"stocks": [{
"stock_symbol": "FFS",
"stock_score": 44
},
{
"stock_symbol": "SMS",
"stock_score": 33
}
]
},
]
}
const data2 = {
"name": "KSE100",
"children": [{
"name": "A",
'points': -9,
"children": [{
"stock_title": "A",
"value": 12,
},
{
"stock_title": "B",
"value": 4,
},
]
},
{
"name": "B",
'points': 20,
"children": [{
"stock_title": "A",
"value": 12,
},
{
"name": "B",
"value": 4,
},
]
},
]
}
//stock_sector_name = name
//sector_score = value
//stocks = children
//stock_symbol = stock_title
//stock_score = value
const keys = {
stock_sector_name: "name",
sector_score: "points",
stocks: "children",
stock_symbol: "stock_title",
stock_score: "value",
indice: "name",
//data: "children"
}
const rename = (value) => {
if (!value || typeof value !== 'object') return value;
if (Array.isArray(value)) return value.map(rename);
return Object.fromEntries(Object
.entries(value)
.map(([k, v]) => [keys[k] || k, rename(v)])
);
}
renamedObj = rename(data);
console.log(renamedObj);
I am trying to write a for or JQuery. Each loop so that It will generate a new JSON Object from an array in a desired format. I want to output a JSON Object from an input JavaScript Array. I have a following input array to convert:
INPUT:
[
{
"parent": "parent_1",
"child": "abc",
"data": "data1"
},
{
"parent": "parent_1",
"child": "def",
"data": "data2"
},
{
"parent": "parent_1",
"child": "ghi",
"data": "data3"
},
{
"parent": "parent_2",
"child": "jkl",
"data": "data4"
},
{
"parent": "parent_2",
"child": "acc",
"data": "data5"
},
{
"parent": "parent_3",
"child": "mjh",
"data": "data6"
},
{
"parent": "parent_3",
"child": "fg1",
"data": "data7"
},
{
"parent": "parent_2",
"child": "dfg",
"data": "data8"
},
{
"parent": "parent_3",
"child": "jkk",
"data": "data9"
},
{
"parent": "parent_4",
"child": "3ff",
"data": "data10"
},
{
"parent": "parent_3",
"child": "mhg",
"data": "data11"
},
{
"parent": "parent_1",
"child": "gnh",
"data": "data12"
}
]
so from above array want to run a for or JQuery. Each loop so that it will generate a new JSON Object in the following format:
OUTPUT:
[
{
"parent_1": {
"child": [
{
"name": "abc",
"data": "data1"
},
{
"name": "def",
"data": "data2"
},
{
"name": "gh1",
"data": "data3"
},
{
"name": "gnh",
"data": "data12"
}
]
}
},
{
"parent_2": {
"child": [
{
"name": "jkl",
"data": "data4"
},
{
"name": "acc",
"data": "data5"
},
{
"name": "dfg",
"data": "data8"
}
]
}
},
{
"parent_3": {
"child": [
{
"name": "mjh",
"data": "data6"
},
{
"name": "fg1",
"data": "data7"
},
{
"name": "jkk",
"data": "data9"
},
{
"name": "mhg",
"data": "data11"
}
]
}
},
{
"parent_4": {
"child": [
{
"name": "3ff",
"data": "data10"
}
]
}
}
]
You could group the data by using parent as key for an object and add the rest of the object to the children array of the group.
This approach does not muate the given data.
const
data = [{ parent: "parent_1", child: "abc", data: "data1" }, { parent: "parent_1", child: "def", data: "data2" }, { parent: "parent_1", child: "ghi", data: "data3" }, { parent: "parent_2", child: "jkl", data: "data4" }, { parent: "parent_2", child: "acc", data: "data5" }, { parent: "parent_3", child: "mjh", data: "data6" }, { parent: "parent_3", child: "fg1", data: "data7" }, { parent: "parent_2", child: "dfg", data: "data8" }, { parent: "parent_3", child: "jkk", data: "data9" }, { parent: "parent_4", child: "3ff", data: "data10" }, { parent: "parent_3", child: "mhg", data: "data11" }, { parent: "parent_1", child: "gnh", data: "data12" }],
result = Object.values(data.reduce((r, { parent, ...o }) => {
r[parent] ??= { [parent]: { children: [] } };
r[parent][parent].children.push(o);
return r;
}, []));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I think you want something like this
const convertArray = (arr, field) => {
const obj = {};
arr.forEach(elem => {
const param = elem[field];
if (!Array.isArray(obj[param])) obj[param] = [];
delete elem[field];
obj[param].push(elem);
});
return Object.keys(obj).map(elem => {
return { [elem]: { child: obj[elem] } };
});
}
then you would use as
convertArray(*array*, "parent")
You can use .reduce function, for example:
var array = [ {name: 'item 1', cate: 'cate-1'}, {name: 'item 2', cate: 'cate-2'} ]
var object = array.reduce(function(obj, item) {
if (!obj[item.cate]) obj[item.cate] = {child: []};
obj[item.cate].child.push(item);
return obj;
}, {})
console.log(object);
You can use the below code for this.
var arr = [{"parent":"parent_1","child":"abc","data":"data1"},{"parent":"parent_1","child":"def","data":"data2"},{"parent":"parent_1","child":"ghi","data":"data3"},{"parent":"parent_2","child":"jkl","data":"data4"},{"parent":"parent_2","child":"acc","data":"data5"},{"parent":"parent_3","child":"mjh","data":"data6"},{"parent":"parent_3","child":"fg1","data":"data7"},{"parent":"parent_2","child":"dfg","data":"data8"},{"parent":"parent_3","child":"jkk","data":"data9"},{"parent":"parent_4","child":"3ff","data":"data10"},{"parent":"parent_3","child":"mhg","data":"data11"},{"parent":"parent_1","child":"gnh","data":"data12"}];
var result = {};
$.each(arr, function (i, item) {
if(!result[item.parent]) {
result[item.parent] = [];
}
var data = {'child': {'name': item.child, 'data': item.data}};
(result[item.parent]).push(data);
});
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I have an object that looks like the following {key: id numbers}
var obj = {
"c4ecb": {id: [3]},
"a4269": {id: [34,36]},
"d76fa": {id: [54,55,60,61]},
"58cb5": {id: [67]}
}
How do I loop each above id in the following array, and return the label?
var response =
{
"success": true,
"data": [
{
"key": "c4ecb",
"name": "fruits",
"options": [
{
"label": "strawberry",
"id": 3
},
{
"label": "apple",
"id": 4
},
{
"label": "pineapple",
"id": 5
},
{
"label": "Other",
"id": 31
}
],
}
]
},
{
"success": true,
"data": [
{
"key": "a4269",
"name": "vegetables",
"options": [
{
"label": "lettuce",
"id": 34
},
{
"label": "cucumber",
"id": 35
},
{
"label": "radish",
"id": 36
}
],
}
]
},
{
"success": true,
"data": [
{
"key": "d76fa",
"name": "pasta",
"options": [
{
"label": "spaghetti",
"id": 54
},
{
"label": "rigatoni",
"id": 55
},
{
"label": "linguine",
"id": 56
},
{
"label": "lasagna",
"id": 60
},
{
"label": "fettuccine",
"id": 61
}
],
}
]
}
Finally, what I want to do is look up the key and return a string of id values.
For example, input c4ecb and output strawberry. Input a4269 and output lettuce, radish. Input d76fa and output "spaghetti, rigatoni, lasagna, fettuccine"
I think to join the multiple labels output into one string I could use something like
array.data.vegetables.map(vegetables => vegetables.value).join(', ')].toString();
So in the end I want to have something like
var fruits = [some code that outputs "strawberry"];
var vegetables = [some code that outputs "lettuce, radish"];
var pasta = [some code that outputs "spaghetti, rigatoni, lasagna, fettuccine"];
What I've tried so far:
The following loop will return the id only if there is one id to be called for: e.g. only in case one where {id: 3} but returns null in cases like {id: 34,36} (because it's looking for '34,36' in id, which doesn't exist - I need to look for each one individually.
response.data.forEach(({key, options}) => {
if (obj[key]) {
options.forEach(({id, label}) => {
if (id == obj[key].id) obj[key].label = label;
});
}
});
console.log(obj)
Filter the response object to focus on the category that matches the id.
Map over the options array and select the items which appear in obj[id].
Finally convert the filtered results to a string.
See filteredLabelsAsString() function below for implementation.
var obj = {
"c4ecb": {"id": [3]},
"a4269": {"id": [34,36]},
"d76fa": {"id": [54,55,60,61]},
"58cb5": {"id": [67]}
}
var response =
[{
"success": true,
"data": [
{
"key": "c4ecb",
"name": "fruits",
"options": [
{
"label": "strawberry",
"id": 3
},
{
"label": "apple",
"id": 4
},
{
"label": "pineapple",
"id": 5
},
{
"label": "Other",
"id": 31
}
],
}
]
},
{
"success": true,
"data": [
{
"key": "a4269",
"name": "vegetables",
"options": [
{
"label": "lettuce",
"id": 34
},
{
"label": "cucumber",
"id": 35
},
{
"label": "radish",
"id": 36
}
],
}
]
},
{
"success": true,
"data": [
{
"key": "d76fa",
"name": "pasta",
"options": [
{
"label": "spaghetti",
"id": 54
},
{
"label": "rigatoni",
"id": 55
},
{
"label": "linguine",
"id": 56
},
{
"label": "lasagna",
"id": 60
},
{
"label": "fettuccine",
"id": 61
}
],
}
]
}];
function filteredLabelsAsString(obj_key, obj, content=response) {
// sanity check: obj must contain obj_key
if (Object.keys(obj).includes(obj_key)) {
return content.filter((item) => {
// filter content using value of obj_key
return item.data[0].key == obj_key;
}).map((item) => {
// item : { success: true, data: [] }
// map over options array
return item.data[0].options.map((opt) => {
// option : {id, label}
// return the label if the id is in the obj object's list
if (obj[item.data[0].key].id.includes(opt.id))
return opt.label;
}).filter((label) => {
// filter out empty items
return label !== undefined;
});
}).join(",");
}
// if obj does not contain obj_key return empty string
return "";
}
console.log("fruits: " + filteredLabelsAsString("c4ecb", obj));
console.log("vegetables: " + filteredLabelsAsString("a4269", obj));
console.log("pasta: " + filteredLabelsAsString("d76fa", obj));
I am trying to make a array which have objects .Actually I need to push object in array but before I have some conditions
I have a array(a is array of objects) .I need to first remove all objects which have property "hidden": true, .I am able to do that like this
I have another b(b is is array of objects).in which I need to collect values from that using parameter fieldNameOrPath .Those value which are deleted from first array which have hidden :true need not to consider in second array .Not to check fieldNameOrPath.Or we can also delete those are deleted from first array using fieldNameOrPath
I trying to fetch values try to get expected result I fail to get
var deletedfieldNameOrPath=[ ];
for (var i = 0; i < a.length; i++) {
if (a[i].hidden) {
deletedfieldNameOrPath.push(a[i].fieldNameOrPath)
delete a[i]
}
}
console.log(a);
console.log(deletedfieldNameOrPath);
var objectarray = []
for (var i = 0; i < b.length; i++) {
for (var k = 0; k < b[i].columns.length; k++) {
var obj = {};
if (deletedfieldNameOrPath.indexOf(b[i].columns.fieldNameOrPath) == -1) {
obj.b[i].columns.fieldNameOrPath = b[i].columns.value;
}
objectarray.push(obj)
}
}
Expected array
[{
Type__c: "pqr",
akritiv__So_Number__c: "a"
}, {
Type__c: "Invoice",
akritiv__So_Number__c: "-"
}, {
Type__c: "inc",
akritiv__So_Number__c: "c"
}, ]
here is fiddle
http://jsfiddle.net/93m4wbh1/
You are pretty close to what you want i think.
I did some minor changes:
First i used splice instead of delete to make sure the object is
removed from the array instead of leaving an empty record.
Then i made sure the object is created and pushed for each column, not each record in each column.
And at last I fixed a little bug preventing
the values to be added to your object, using the [] (like on arrays).
var a = [{
"hidden": true,
"fieldNameOrPath": "Name",
}, {
"hidden": true,
"fieldNameOrPath": "akritiv__Account__r.Name",
}, {
"hidden": false,
"fieldNameOrPath": "Type__c",
}, {
"hidden": false,
"fieldNameOrPath": "akritiv__So_Number__c",
}];
var deletedfieldNameOrPath = [];
var collectNameOrPath = [];
for (var i = 0; i < a.length; i) {
if (a[i].hidden) {
deletedfieldNameOrPath.push(a[i].fieldNameOrPath)
a.splice(i, 1);
continue;
} else {
collectNameOrPath.push(a[i].fieldNameOrPath);
}
i ++;
}
console.log(a);
console.log(deletedfieldNameOrPath);
[{
Type__c: "pqr",
akritiv__So_Number__c: "a"
}, {
Type__c: "Invoice",
akritiv__So_Number__c: "-"
}, {
Type__c: "inc",
akritiv__So_Number__c: "c"
},
]
var b = [{
"columns": [{
"value": "a0RK0000002l3AB",
"fieldNameOrPath": "Name"
}, {
"value": "Sun Life Financial",
"fieldNameOrPath": "akritiv__Account__r.Name"
}, {
"value": "pqr",
"fieldNameOrPath": "Type__c"
}, {
"value": "a",
"fieldNameOrPath": "akritiv__So_Number__c"
}]
}, {
"columns": [{
"value": "a0RK0000002l3ac",
"fieldNameOrPath": "Name"
}, {
"value": "Scottish Power",
"fieldNameOrPath": "akritiv__Account__r.Name"
}, {
"value": "Invoice",
"fieldNameOrPath": "Type__c"
}, {
"value": "-",
"fieldNameOrPath": "akritiv__So_Number__c"
}]
}, {
"columns": [{
"value": "a0RK0000002l3aC",
"fieldNameOrPath": "Name"
}, {
"value": "FirstEnergy",
"fieldNameOrPath": "akritiv__Account__r.Name"
}, {
"value": "inc",
"fieldNameOrPath": "Type__c"
}, {
"value": "c",
"fieldNameOrPath": "akritiv__So_Number__c"
}]
}]
var objectarray = []
for (var i = 0; i < b.length; i++) {
var obj = {};
for (var k = 0; k < b[i].columns.length; k++) {
if (deletedfieldNameOrPath.indexOf(b[i].columns[k].fieldNameOrPath) == -1) {
obj[b[i].columns[k].fieldNameOrPath] = b[i].columns[k].value;
}
}
objectarray.push(obj)
}
console.log(objectarray);
There is no reason to delete elements from the array.
Try this.
var a = [{
"hidden": true,
"fieldNameOrPath": "Name",
}, {
"hidden": true,
"fieldNameOrPath": "akritiv__Account__r.Name",
}, {
"hidden": false,
"fieldNameOrPath": "Type__c",
}, {
"hidden": false,
"fieldNameOrPath": "akritiv__So_Number__c",
}];
var collectNameOrPath =
a.filter(function(o) { return !o.hidden })
.map(function(o) { return o.fieldNameOrPath });
console.log(collectNameOrPath);
var b = [{
"columns": [{
"value": "a0RK0000002l3AB",
"fieldNameOrPath": "Name"
}, {
"value": "Sun Life Financial",
"fieldNameOrPath": "akritiv__Account__r.Name"
}, {
"value": "pqr",
"fieldNameOrPath": "Type__c"
}, {
"value": "a",
"fieldNameOrPath": "akritiv__So_Number__c"
}]
}, {
"columns": [{
"value": "a0RK0000002l3ac",
"fieldNameOrPath": "Name"
}, {
"value": "Scottish Power",
"fieldNameOrPath": "akritiv__Account__r.Name"
}, {
"value": "Invoice",
"fieldNameOrPath": "Type__c"
}, {
"value": "-",
"fieldNameOrPath": "akritiv__So_Number__c"
}]
}, {
"columns": [{
"value": "a0RK0000002l3aC",
"fieldNameOrPath": "Name"
}, {
"value": "FirstEnergy",
"fieldNameOrPath": "akritiv__Account__r.Name"
}, {
"value": "inc",
"fieldNameOrPath": "Type__c"
}, {
"value": "c",
"fieldNameOrPath": "akritiv__So_Number__c"
}]
}]
var nameOrPathValues = b.map(function(o) {
var result = {};
o.columns.forEach(function(c) {
result[c.fieldNameOrPath] = c.value;
});
return result;
});
console.log(nameOrPathValues);
var objectarray = nameOrPathValues.map(function(o) {
var result = {};
collectNameOrPath.forEach(function(name) {
result[name] = o[name];
});
return result;
});
console.log(objectarray);
I have a list of records and i convert it to json:
[ { "id": 1, "name": "A", "parentID": 0, "hasItems": "true" },
{ "id": 2, "name": "B", "parentID": 1, "hasItems": "false" },
{ "id": 3, "name": "C", "parentID": 1, "hasItems": "false" },
{ "id": 4, "name": "D", "parentID": 0, "hasItems": "false" }
]
Now i want create a KendoTreeView from above json data:
<div id="treeview55"></div>
<script>
dtSrc = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: "http://localhost:1132/Discontent/GetTreeNodes",
dataType: "json"
}
},
,
schema:{
model: {
id: 'id',
parentId: 'parentID',
name: 'name'
}
}
});
$("#treeview55").kendoTreeView({
dataSource: dtSrc,
dataTextField: "name",
dataValueField: 'id',
});
Result:
A
B
C
D
My Expected Result:
> A
B
C
D
My question:
Is there any way to create a KendoTreeView with above expected result (cascade children and parents) by above json data???
Refer below part of code will hep you to solve your problem
<div id="tree"></div>
<script>
var flatData = [ { "id": 1, "text": "A", "parent": 0, "hasItems": "true" },
{ "id": 2, "text": "B", "parent": 1, "hasItems": "false" },
{ "id": 3, "text": "C", "parent": 1, "hasItems": "false" },
{ "id": 4, "text": "D", "parent": 0, "hasItems": "false" }
];
function processTable(data, idField, foreignKey, rootLevel) {
var hash = {};
for (var i = 0; i < data.length; i++) {
var item = data[i];
var id = item[idField];
var parentId = item[foreignKey];
hash[id] = hash[id] || [];
hash[parentId] = hash[parentId] || [];
item.items = hash[id];
hash[parentId].push(item);
}
return hash[rootLevel];
}
// the tree for visualizing data
$("#tree").kendoTreeView({
dataSource: processTable(flatData, "id", "parent", 0),
loadOnDemand: false
});
</script>
i just prepare a sample based on your sample data, i hopes it helps to you.
Find answer from this jsbin
At this moment, no. The Kendo UI TreeView works with hierarchical data, and the above is a flattened hierarchy. You need to process the data it so that it becomes hierarchical, like shown in this excellent answer by Jon Skeet.