I want to append json data to bring tree view structure. Initially I had created static tree view this is my fiddle code with json tree view: https://jsfiddle.net/ak3zLzgd/6/
Here I have challenges to append three level level json data instead of static html code.
Exactly inside retailer digital marketing > sub-ToI > semi-sub-TOI > super-sub-TOI all the thirditems json array is appending ti first value only . For more info check this fiddle: https://jsfiddle.net/ak3zLzgd/6/
var json = {
"category": [{
"title": "Customer Satisfaction",
"id": "nnanet:category/certified-pre-owned",
"items": [{
"title": "Bulletins",
"id": "nnanet:category/customer-satisfaction/bulletins",
"thirditems": [{
"title": "TOI",
"id": "nnanet:category/retailer-digital-marketing/toi"
}, {
"title": "TOI",
"id": "nnanet:category/retailer-digital-marketing/toi"
}]
}, {
"title": "Consumer Affairs",
"id": "nnanet:category/customer-satisfaction/consumer-affairs"
}, {
"title": "Loyalty",
"id": "nnanet:category/customer-satisfaction/loyalty",
"thirditems": [{
"title": "TOI",
"id": "nnanet:category/retailer-digital-marketing/toi"
}, {
"title": "TOI",
"id": "nnanet:category/retailer-digital-marketing/toi"
}]
}]
}, {
"title": "Retailer Digital Marketing",
"id": "nnanet:category/retailer-digital-marketing",
"items": [{
"title": "TOI",
"id": "nnanet:category/retailer-digital-marketing/toi",
"thirditems": [{
"title": "TOI",
"id": "nnanet:category/retailer-digital-marketing/toi"
}, {
"title": "TOI",
"id": "nnanet:category/retailer-digital-marketing/toi"
}]
}, {
"title": "Basics",
"id": "nnanet:category/retailer-digital-marketing/reference-guide/basics"
}, {
"title": "International",
"id": "nnanet:category/retailer-digital-marketing/international"
}]
}, {
"title": "Finance Today",
"id": "nnanet:category/customer-satisfaction/bulletins/finance-today",
"items": [{
"title": "TOI",
"id": "nnanet:category/retailer-digital-marketing/toi",
"thirditems": [{
"title": "TOI",
"id": "nnanet:category/retailer-digital-marketing/toi"
}, {
"title": "TOI",
"id": "nnanet:category/retailer-digital-marketing/toi"
}]
}, {
"title": "Basics",
"id": "nnanet:category/retailer-digital-marketing/reference-guide/basics"
}, {
"title": "International",
"id": "nnanet:category/retailer-digital-marketing/international"
}]
}, {
"title": "Annual",
"id": "nnanet:category/customer-satisfaction/bulletins/finance-today/revenue/annual",
"items": [{
"title": "TOI",
"id": "nnanet:category/retailer-digital-marketing/toi"
}, {
"title": "Basics",
"id": "nnanet:category/retailer-digital-marketing/reference-guide/basics"
}, {
"title": "International",
"id": "nnanet:category/retailer-digital-marketing/international"
}]
}]
};
function expander(){
var tree = document.querySelectorAll('ul.tree a:not(:last-child)');
for(var i = 0; i < tree.length; i++){
tree[i].addEventListener('click', function(e) {
var element = e.target.parentElement; //actually this is just the elem itself
var parent = element.parentElement
var opensubs = parent.querySelectorAll(':scope .open');
console.log(opensubs);
var classList = element.classList;
if(opensubs.length !=0) {
for(var i = 0; i < opensubs.length; i++){
opensubs[i].classList.remove('open');
}
}
classList.add('open');
});
}
}
$(function(){
var tree = $("ul.tree");
$.each(json.category,function(category){
var categoryValue = json.category[category];
tree.append('<li>'+categoryValue.title+'<ul></ul></li>');
var el = tree.children("li").children("ul");
$.each(categoryValue.items,function(itemId){
var item = categoryValue.items[itemId];
$(el[category]).append('<li>'+item.title+'</li>');
if(item.thirditems){
$(el[category]).children("li").append('<ul></ul>');
var el1 = el.children("li").children("ul");
$.each(item.thirditems,function(thirdItemId){
var thirdItem = item.thirditems[thirdItemId];
console.log(el1[itemId]);
$(el1[itemId]).append('<li>'+thirdItem.title+'<ul></ul></li>');
});
}
});
});
expander();
});
Output : check this fiddle : https://jsfiddle.net/ak3zLzgd/6/
Related
Check for the decimal id and group them accordingly.
Below are the sample and recommended JSON's
Sample JSON
{
"results": [
{
"name": "Download",
"id": "1.1.1"
},
{
"name": "Download",
"id": "1.2"
},
{
"name": "Download",
"id": "1.3.2"
},
{
"name": "Download",
"id": "2"
},
{
"name": "Download",
"id": "2.3"
},
{
"name": "Download",
"id": "3.2"
},
{
"name": "Download",
"id": "3.5"
},
{
"name": "Download",
"id": "4.2"
}
]
}
Would like to iterate and Re-structure the above JSON into below recommended format.
Logic: Should check the id(with and without decimals) and group them based on the number.
For Example:
1, 1.1, 1.2.3, 1.4.5 => data1: [{id: 1},{id: 1.1}....]
2, 2.3, 2.3.4 => data2: [{id: 2},{id: 2.3}....]
3, 3.1 => data3: [{id: 3},{id: 3.1}]
Recommended JSON
{
"results": [
{
"data1": [
{
"name": "Download",
"id": "1.1.1"
},
{
"name": "Download",
"id": "1.2"
},
{
"name": "Download",
"id": "1.3.2"
}
]
},
{
"data2": [
{
"name": "Download",
"id": "2"
},
{
"name": "Download",
"id": "2.3"
}
]
},
{
"data3": [
{
"name": "Download",
"id": "3.2"
},
{
"name": "Download",
"id": "3.5"
}
]
},
{
"data4": [
{
"name": "Download",
"id": "4.2"
}
]
}
]
}
I have tried the below solution but it doesn't group the object
var formatedJSON = [];
results.map(function(d,i) {
formatedJSON.push({
[data+i]: d
})
});
Thanks in advance.
You can use reduce like this. The idea is to create a key-value pair for each data1, data2 etc so that values in this object are the values you need in the final array. Then use Object.values to get those as an array.
const sampleJson = {"results":[{"name":"Download","id":"1.1.1"},{"name":"Download","id":"1.2"},{"name":"Download","id":"1.3.2"},{"name":"Download","id":"2"},{"name":"Download","id":"2.3"},{"name":"Download","id":"3.2"},{"name":"Download","id":"3.5"},{"name":"Download","id":"4.2"}]}
const grouped = sampleJson.results.reduce((a, v) => {
const key = `data${parseInt(v.id)}`;
(a[key] = a[key] || {[key]: []})[key].push(v);
return a;
},{});
console.log({results: Object.values(grouped)})
One liner / Code-golf:
let s={"results":[{"name":"Download","id":"1.1.1"},{"name":"Download","id":"1.2"},{"name":"Download","id":"1.3.2"},{"name":"Download","id":"2"},{"name":"Download","id":"2.3"},{"name":"Download","id":"3.2"},{"name":"Download","id":"3.5"},{"name":"Download","id":"4.2"}]},k;
console.log({results:Object.values(s.results.reduce((a,v)=>(k=`data${parseInt(v.id)}`,(a[k] = a[k]||{[k]:[]})[k].push(v),a),{}))})
Here you go:
var data = {
"results": [
{
"name": "Download",
"id": "1.1.1"
},
{
"name": "Download",
"id": "1.2"
},
{
"name": "Download",
"id": "1.3.2"
},
{
"name": "Download",
"id": "2"
},
{
"name": "Download",
"id": "2.3"
},
{
"name": "Download",
"id": "3.2"
},
{
"name": "Download",
"id": "3.5"
},
{
"name": "Download",
"id": "4.2"
}
]
};
let newSet = new Set();
data.results.forEach(e => {
let key = e.id.substring(0, e.id.indexOf('.'));
console.log(key);
if (newSet.has(key) == false) {
newSet.add(key);
newSet[key] = [];
}
newSet[key].push(e.id);
});
console.log(newSet);
Here's how you'd do it:
var data = {
"results": [
{
"name": "Download",
"id": "1.1.1"
},
{
"name": "Download",
"id": "1.2"
},
{
"name": "Download",
"id": "1.3.2"
},
{
"name": "Download",
"id": "2"
},
{
"name": "Download",
"id": "2.3"
},
{
"name": "Download",
"id": "3.2"
},
{
"name": "Download",
"id": "3.5"
},
{
"name": "Download",
"id": "4.2"
}
]
};
var newData = {
"results": {}
};
data.results.forEach(item => {
var num = item.id.slice(0, 1);
if (newData.results["data" + num]) {
newData.results["data" + num].push(item);
} else {
newData.results["data" + num] = [item];
}
})
data = newData;
console.log(data);
What this does is it iterates through each item in results, gets the number at the front of this item's id, and checks if an array of the name data-{num} exists. If the array exists, it's pushed. If it doesn't exist, it's created with the item.
let input = getInput();
let output = input.reduce((acc, curr)=>{
let {id} = curr;
let majorVersion = 'name' + id.split('.')[0];
if(!acc[majorVersion]) acc[majorVersion]= [];
acc[majorVersion].push(curr);
return acc;
},{})
console.log(output)
function getInput(){
return [
{
"name": "Download",
"id": "1.1.1"
},
{
"name": "Download",
"id": "1.2"
},
{
"name": "Download",
"id": "1.3.2"
},
{
"name": "Download",
"id": "2"
},
{
"name": "Download",
"id": "2.3"
},
{
"name": "Download",
"id": "3.2"
},
{
"name": "Download",
"id": "3.5"
},
{
"name": "Download",
"id": "4.2"
}
]
}
One solution with RegEx for finer control as it would differentiate easily between 1 and 11.
Also this will make sure that even if the same version comes in end(say 1.9 in end) it will put it back in data1.
let newArr2 = ({ results }) =>
results.reduce((acc, item) => {
let key = "data" + /^(\d+)\.?.*/.exec(item.id)[1];
let found = acc.find(i => key in i);
found ? found[key].push(item) : acc.push({ [key]: [item] });
return acc;
}, []);
var data = [
{
"text": "BEHIND A COMMON MEAL: POLYPHENOLS IN FOOD ",
"id": "445",
"parentid": ""
},
{
"text": "2.2 First Course: Pasta With Tomato Sauce (Polyphenols in Wheat Bran and Tomato Byproducts)",
"id": "441",
"parentid": "445"
},
{
"text": "2.3 A Fresh Side Dish: Mixed Salad (Polyphenols From Fennel, Carrot)",
"id": "442",
"parentid": "445"
},
{
"text": "hello mr.sujai",
"id": "448",
"parentid": "445"
},
{
"text": "polyhierarchy",
"id": "449",
"parentid": "445"
},
{
"text": "INTRODUCTION",
"id": "452",
"parentid": ""
},
{
"text": "1.2 The Tight Biochemical Connection Between Vegetables and Their Byproducts",
"id": "440",
"parentid": "452"
},
{
"text": "OTHER OFF-THE-MENU MISCELLANEOUS",
"id": "454",
"parentid": ""
},
{
"text": "SOMETHING TO DRINK",
"id": "456",
"parentid": ""
},
{
"text": "3.1 Orange Juice (Polyphenols From Orange Byproducts)",
"id": "443",
"parentid": "456"
},
{
"text": "3.2 Wine (Polyphenols From Grape and Wine Byproducts)",
"id": "444",
"parentid": "456"
},
{
"text": "understandings",
"id": "451",
"parentid": "456"
},
{
"text": "Polyphenols",
"id": "453",
"parentid": "451"
},
{
"text": "this is test",
"id": "458",
"parentid": "455"
},
{
"text": "polyhierarchy",
"id": "449",
"parentid": "458"
},
{
"text": "hello",
"id": "447",
"parentid": "449"
},
{
"text": "hi",
"id": "459",
"parentid": "447"
},
{
"text": "polyhierarchy",
"id": "449",
"parentid": "459"
},
{
"text": "testing",
"id": "457",
"parentid": "458"
},
{
"text": "hi test",
"id": "450",
"parentid": "457"
},
{
"text": "speech",
"id": "446",
"parentid": "450"
}]
function jsonTree() {
// Keep a fast lookup dictionary
var dictionary = {};
for (var i = 0; i < data.length; i++) {
dictionary[data[i].id] = data[i];
}
for (var i = 0; i < data.length; i++) {
if (data[i].parentid == 449) {
var test = "";
}
if (data[i].parentid) {
var parent = dictionary[data[i].parentid];
arrData = parent;
if (parent) {
if (!parent.children) {
parent.children = [];
}
parent.children.push(data[i]);
// arrData.children.push(data[i]);
}
}
}
var arrData = [];
for (var i = 0; i < data.length; i++) {
if (data[i].parentid == 455) {
arrData.push(data[i]);
}
}
document.getElementById("test").innerHTML = JSON.stringify(arrData);
return false;
}
polyhierarchy term having different parent.
for (var i = 0; i < data.length; i++) {
dictionary[data[i].id] = data[i];
}
in this place same id is replaced. polyhierarchy having id is 449. when add to dictionary it is replaced.
Tree structure should be
1. BEHIND A COMMON MEAL: POLYPHENOLS IN FOOD
polyhierarchy
2. this is test
polyhierarchy
hello
hi
polyhierarchy
i need array with parent, child relationship.
There are a few mistakes.
You have duplicate id's for your polyhierarchie element. Because you're building a dictionary to lookup your ids, you're overwriting your child element the second/subsequent time you add it to your object.
{
"text": "polyhierarchy",
"id": "449", //<-- duplicate
"parentid": "459"
}
You have non existant parentIds.
{
"text": "SOMETHING TO DRINK",
"id": "456",
"parentid": "455" // <--- doesn't exist
}
The code got a little more complex than anticipated because of those two issues.
function mapData (data) {
//build a dictionary for: id -> [eles]
var map = data.reduce ((obj, ele) => {
obj[ele.id] = [ //let's make the lookup an array, to support multiple elements with the same id
...obj[ele.id] || [], //keep the existing elements or initialize it to an array
{...ele, children: []}
];
return obj
}, {});
return Object.keys (map).reduce ((arr, key) => {
let eles = map [key] || []; //process all elements
eles.forEach (ele => {
let parents = map [ele.parentid] || [];
let parent = parents [0];
if (!parent) {
parent = map [ele.parentid] = {children: [], root: true}
}
parent.children.push (ele);
if (parent.root && !~arr.indexOf (parent)) arr.push (parent);
});
return arr;
},[])
}
console.log (mapData (data))
I have nested children in my document i want find document any children._id
my document look like below.
For Example:
I want this children._id "PxX4EYMYVDOphx8XU" how to find this document.
[{
"_id": "v4jdHchuogyumed7f",
"name": "products",
"children": [{
"_id": "fDE1kyR081Y44aO7h",
"name": "Clothes",
"children": [{
"_id": "l464EYMYVDOphx8XU",
"name": "Shoes",
"children": [{
"_id": "PxX4EYMYVDOphx8XU",
"name": "Black Shoes"
}]
}, {
"_id": "gUHcdTuPxXhauIWaZ",
"name": "Shirts"
}]
}, {
"_id": "svcdrpPybHJf0KiBi",
"name": "Flowers",
"children": [{
"_id": "gdEk85byoRCWxStTf",
"name": "Red Flowers"
}]
}]
}]
You need to recursively walk the object and match _id then return the parent object. An example could be.
var walk = returnExports;
var x = [{
"_id": "v4jdHchuogyumed7f",
"name": "products",
"children": [{
"_id": "fDE1kyR081Y44aO7h",
"name": "Clothes",
"children": [{
"_id": "l464EYMYVDOphx8XU",
"name": "Shoes",
"children": [{
"_id": "PxX4EYMYVDOphx8XU",
"name": "Black Shoes"
}]
}, {
"_id": "gUHcdTuPxXhauIWaZ",
"name": "Shirts"
}]
}, {
"_id": "svcdrpPybHJf0KiBi",
"name": "Flowers",
"children": [{
"_id": "gdEk85byoRCWxStTf",
"name": "Red Flowers"
}]
}]
}];
var find = 'PxX4EYMYVDOphx8XU';
var children;
var parent;
walk(x, Object.keys, function(value, prop, object, depth) {
if (prop === 'children' && Array.isArray(value)) {
children = value;
walk.STOP;
}
if (prop === '_id' && value === find) {
parent = children.find(function(obj) {
return object._id === find;
});
return walk.BREAK;
}
});
console.log(parent);
<script src="https://rawgithub.com/Xotic750/object-walk-x/master/lib/object-walk-x.js"></script>
https://www.npmjs.com/package/object-walk-x if you don't want to write your own object walker.
Hi I have a json array in the below format.
{
"data": {
"title": "MainNode"
},
"children": [{
"data": {
"title": "Firstchild",
"description": "Texttexttext"
},
"children": [{
"data": {
"title": "Firstchildschild",
"description": "Texttexttext"
},
"children": [{
"data": {
"title": "FirstchildschildsChild",
"description": "Texttexttext"
}
}]
}, {
"data": {
"title": "FirstchildsSecondchild",
"description": "Texttexttext"
},
"children": [{
"data": {
"title": "FirstchildsSecondchildsChild",
"description": "Texttexttext"
}
}]
}]
}]
}
I have to read the array based on the title text value and list that particular data and its sub data.
For eg. If my input (title value will get from the http URL as follows) is "Firstchild/Firstchildschild/" then I have to list FirstchildschildsChild and its description.
If my input is input is /Firstchild/ then I have to list Firstchildschild & FirstchildsSecondchild data and its sub childs name.
Using jquery how can I fetch records as I mentioned above. Please advise the best way to process this json instead of using lot of loops?
Ok just for these necessities (and believe this is really a big necessity) i had invented an Object method called Object.prototype.getNestedValue() which dynamically fetches you the nested value from deeply nested Objects. All you need to provide is a string for the properties and a number for the array indices in the proper order. OK lets see...
Object.prototype.getNestedValue = function(...a) {
return a.length > 1 ? (this[a[0]] !== void 0 && this[a[0]].getNestedValue(...a.slice(1))) : this[a[0]];
};
var JSONobj = {
"data": {
"title": "MainNode"
},
"children": [{
"data": {
"title": "Firstchild",
"description": "Texttexttext"
},
"children": [{
"data": {
"title": "Firstchildschild",
"description": "Texttexttext"
},
"children": [{
"data": {
"title": "FirstchildschildsChild",
"description": "Texttexttext"
}
}]
}, {
"data": {
"title": "FirstchildsSecondchild",
"description": "Texttexttext"
},
"children": [{
"data": {
"title": "FirstchildsSecondchildsChild",
"description": "Texttexttext"
}
}]
}]
}]
},
value = JSONobj.getNestedValue("children",0,"children",0,"data","title");
console.log(value); // Firstchildschild
var a = "children",
b = 0,
c = "data",
d = "title";
value2 = JSONobj.getNestedValue(...[a,b,a,b,c,d])
console.log(value2); // Firstchildschild
It also has a sister called Object.prototype.setNestedValue().
var obj = jQuery.parseJSON( '
"data": {
"title": "MainNode"
},
"children": [{
"data": {
"title": "Firstchild",
"description": "Texttexttext"
},
"children": [{
"data": {
"title": "Firstchildschild",
"description": "Texttexttext"
},
"children": [{
"data": {
"title": "FirstchildschildsChild",
"description": "Texttexttext"
}
}]
}, {
"data": {
"title": "FirstchildsSecondchild",
"description": "Texttexttext"
},
"children": [{
"data": {
"title": "FirstchildsSecondchildsChild",
"description": "Texttexttext"
}
}]
}]
}]
}' );
alert( obj.name === "data" );
You have to parse the element
obj.name === "data"
in the next link
Kindly help me in sorting the below JSON list in the controller and display in the view.
Actually orderBy filter sorting one level, But I need it sort even for childs recursively.
Input:
R2
-->S4
------>T5
------>T4
-->S3
R1
-->S2
------>T2
------>T1
-->S1
Output:
R1
-->S1
------>T1
------>T2
-->S2
R2
-->S3
------>T4
------>T5
-->S4
Please find the sample in Plunker.
http://plnkr.co/edit/JslHwJ1CBREKf6FgYHaZ?p=preview
var sortNames = function(arr){
arr = arr.sort(function(a,b){
return a.name > b.name;
})
for (var i = 0; i < arr.length; i++){
if (arr[i].childs){
sortNames(arr[i].childs)
}
}
return arr;
}
var names = [
{
"name": "Root1",
"Id": "2f3d17cb-d9e2-4e99-882d-546767f2765d",
"status": "",
"dispName": "",
"imageURL": "",
"childCount": "",
"childs": [
{
"name": "Sub1",
"Id": "ff8b3896-3b80-4e1b-be89-52a82ec9f98f",
"childs": [
{
"name": "Template1",
"Id": "ff8b3896-3b80-4e1b-be89-52a82ec9f981",
"status": "",
"dispName": "",
"imageURL": ""
},
{
"name": "Template2",
"Id": "ff8b3896-3b80-4e1b-be89-52a82ec9f982",
"status": "",
"dispName": "",
"imageURL": ""
}
]
},
{
"name": "Template3",
"Id": "ff8b3896-3b80-4e1b-be89-52a82ec9f981"
}
]
},
{
"name": "Root2",
"Id": "ea0586e7-02cf-4359-94ba-8d9623590dfe",
"childs": [
{
"name": "Sub2",
"Id": "6f1b3a60-d295-413e-92ef-1c713446e6c9",
"childs": [
{
"name": "Template4",
"Id": "6f1b3a60-d295-413e-92ef-1c713446e6c1"
},
{
"name": "Template5",
"Id": "6f1b3a60-d295-413e-92ef-1c713446e6c2"
}
]
}
]
}
];
sortNames(names);