Unable to push children into parent based on parentId using JS - javascript

I am unable to push childEntries into parent based on parentId using JS. Actually I need to populate the data into a tree view table.
Here is the JSON I got from API
[{
"displayName": "",
"order": 1,
"status": "Active",
"description": "Application Top Section",
"createDate": "2020-01-01 12:00:00",
"parentId": 0,
"modifiedDate": "2020-01-01 12:00:00",
"id": 0,
"type": "section"
}, {
"displayName": "",
"order": 1,
"status": "Active",
"description": "Application Side Navigation Section",
"createDate": "2020-01-01 12:00:00",
"parentId": 1,
"modifiedDate": "2020-01-01 12:00:00",
"id": 1,
"type": "section"
}, {
"displayName": "Puente Dashboard",
"order": 1,
"status": "Active",
"description": "Application Dashboard",
"createDate": "2020-01-01 12:00:00",
"parentId": 1,
"modifiedDate": "2020-01-01 12:00:00",
"id": 2,
"type": "link"
}, {
"displayName": "Security",
"order": 2,
"status": "Active",
"description": "Security Management",
"createDate": "2020-01-01 12:00:00",
"parentId": 1,
"modifiedDate": "2020-01-01 12:00:00",
"id": 3,
"type": "link"
}, {
"displayName": "User",
"order": 1,
"status": "Active",
"description": "User Management",
"createDate": "2020-01-01 12:00:00",
"parentId": 3,
"modifiedDate": "2020-01-01 12:00:00",
"id": 4,
"type": "link"
}, {
"displayName": "Role",
"order": 2,
"status": "Active",
"description": "Role Management",
"createDate": "2020-01-01 12:00:00",
"parentId": 3,
"modifiedDate": "2020-01-01 12:00:00",
"id": 5,
"type": "link"
}, {
"displayName": "Widget",
"order": 3,
"status": "Active",
"description": "Widget Management",
"createDate": "2020-01-01 12:00:00",
"parentId": 3,
"modifiedDate": "2020-01-01 12:00:00",
"id": 6,
"type": "link"
}]
And expected JSON is
[{
"displayName": "",
"order": 1,
"status": "Active",
"description": "Application Top Section",
"createDate": "2020-01-01 12:00:00",
"parentId": 0,
"modifiedDate": "2020-01-01 12:00:00",
"id": 0,
"type": "section"
},
{
"displayName": "",
"order": 1,
"status": "Active",
"description": "Application Side Navigation Section",
"createDate": "2020-01-01 12:00:00",
"parentId": 1,
"modifiedDate": "2020-01-01 12:00:00",
"id": 1,
"type": "section",
"childEntries": [{
"displayName": "Puente Dashboard",
"order": 1,
"status": "Active",
"description": "Application Dashboard",
"createDate": "2020-01-01 12:00:00",
"parentId": 1,
"modifiedDate": "2020-01-01 12:00:00",
"id": 2,
"type": "link"
},
{
"displayName": "Security",
"order": 2,
"status": "Active",
"description": "Security Management",
"createDate": "2020-01-01 12:00:00",
"parentId": 1,
"modifiedDate": "2020-01-01 12:00:00",
"id": 3,
"type": "link",
"childEntries": [{
"displayName": "User",
"order": 1,
"status": "Active",
"description": "User Management",
"createDate": "2020-01-01 12:00:00",
"parentId": 3,
"modifiedDate": "2020-01-01 12:00:00",
"id": 4,
"type": "link"
},
{
"displayName": "Role",
"order": 2,
"status": "Active",
"description": "Role Management",
"createDate": "2020-01-01 12:00:00",
"parentId": 3,
"modifiedDate": "2020-01-01 12:00:00",
"id": 5,
"type": "link"
},
{
"displayName": "Widget",
"order": 3,
"status": "Active",
"description": "Widget Management",
"createDate": "2020-01-01 12:00:00",
"parentId": 3,
"modifiedDate": "2020-01-01 12:00:00",
"id": 6,
"type": "link"
}
]
}
]
}
]
Using below code only I am able to add "kind","childEntries" and "expanded". But ultimately I am not getting my expected JSON.
this.widgetsource.forEach(function (element) { if(element.parentId == 1 || element.parentId == 0 ){ element.kind = "dir"; element.expanded = false; element.childEntries = []; }
Here in this.widgetsource I have stored the raw JSON.
Could you please help me here.
Thanks in advance.

You can check if its a child when parent is not equal to itself, then find the parent and add in child list.
const parsedObject = JSON.parse(`[{ "displayName": "", "order": 1, "status": "Active", "description": "Application Top Section", "createDate": "2020-01-01 12:00:00", "parentId": 0, "modifiedDate": "2020-01-01 12:00:00", "id": 0, "type": "section" }, { "displayName": "", "order": 1, "status": "Active", "description": "Application Side Navigation Section", "createDate": "2020-01-01 12:00:00", "parentId": 1, "modifiedDate": "2020-01-01 12:00:00", "id": 1, "type": "section" }, { "displayName": "Puente Dashboard", "order": 1, "status": "Active", "description": "Application Dashboard", "createDate": "2020-01-01 12:00:00", "parentId": 1, "modifiedDate": "2020-01-01 12:00:00", "id": 2, "type": "link" }, { "displayName": "Security", "order": 2, "status": "Active", "description": "Security Management", "createDate": "2020-01-01 12:00:00", "parentId": 1, "modifiedDate": "2020-01-01 12:00:00", "id": 3, "type": "link" }, { "displayName": "User", "order": 1, "status": "Active", "description": "User Management", "createDate": "2020-01-01 12:00:00", "parentId": 3, "modifiedDate": "2020-01-01 12:00:00", "id": 4, "type": "link" }, { "displayName": "Role", "order": 2, "status": "Active", "description": "Role Management", "createDate": "2020-01-01 12:00:00", "parentId": 3, "modifiedDate": "2020-01-01 12:00:00", "id": 5, "type": "link" }, { "displayName": "Widget", "order": 3, "status": "Active", "description": "Widget Management", "createDate": "2020-01-01 12:00:00", "parentId": 3, "modifiedDate": "2020-01-01 12:00:00", "id": 6, "type": "link" }]`);
/**
* converting into a map for efficient access by ID id:Object.
*/
const idMap = parsedObject.reduce((accum,obj)=>{
accum[obj.id] = obj;
return accum;
},{});
const categorisedList = [];
parsedObject.forEach(obj=>{
if(obj.parentId === obj.id){
categorisedList.push(obj);
}else{
const parent = idMap[obj.parentId];
if(!parent.childEntries){
parent.childEntries=[];
}
parent.childEntries.push(obj);
}
});
console.log(categorisedList);
//If you need as JSON String.
const json = JSON.stringify(categorisedList);

Related

Tree massiv get all the links of the elements

I have and object literal that is essentially a tree that does not have a fixed number of levels.
How can I search for a tree for a particular node, and then return this node with connection parameters when it is found in a spectacular javascript manner?
var data = [{
title: 'topNode',
id: 1,
children: [{
title: 'node1',
id: 2,
children: [{
title: 'randomNode_1',
id: 3,
},
{
title: 'node2',
id: 4,
children: [{
title: 'randomNode_2',
id: 5,
children: [{
title: 'node2',
id: 1111,
children: [{
title: 'randomNode_3',
id: 1232,
}]
}]
}]
}
]
}]
}];
tree build   what should be done
tree built from api
serializeGoals: state => type => {
const _goals = JSON.parse(JSON.stringify(state.goals))
return {
title: 'Стратегия',
expand: true,
forst: true,
children: _goals.filter((item) => {
if (item.type !== null && type.some(typeID => typeID === item.type.id)) {
item.shadow = true
} else if (item.type !== null && type.length > 0) {
item.shadow = false
item.type.color = '#ECECEC'
}
item.children = _goals.filter((children) => {
if (children.parent_id === item.id) {
if (children.type !== null && type.some(typeID => typeID === children.type.id)) {
children.shadow = true
} else if (children.type !== null && type.length > 0) {
children.type.color = '#ECECEC'
children.shadow = false
}
return true
}
return false
})
return item.parent_id === null
})
}
}
Get api server JSON array
parent_id - element parent
[{
"id": 5,
"parent_id": null,
"responsible_id": null,
"type_id": 4,
"title": "Тестовая цель - 5",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 4, "title": "Персонал", "color": "#6190e8"}
}, {
"id": 7,
"parent_id": null,
"responsible_id": null,
"type_id": 4,
"title": "Тестовая цель - 7",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 4, "title": "Персонал", "color": "#6190e8"}
}, {
"id": 9,
"parent_id": null,
"responsible_id": null,
"type_id": 4,
"title": "Тестовая цель - 9",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 4, "title": "Персонал", "color": "#6190e8"}
}, {
"id": 11,
"parent_id": null,
"responsible_id": null,
"type_id": 3,
"title": "Тестовая цель - 11",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 3, "title": "Процессы", "color": "#13ce66"}
}, {
"id": 13,
"parent_id": null,
"responsible_id": null,
"type_id": 4,
"title": "Тестовая цель - 13",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 4, "title": "Персонал", "color": "#6190e8"}
}, {
"id": 15,
"parent_id": null,
"responsible_id": null,
"type_id": 2,
"title": "Тестовая цель - 15",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 2, "title": "Клиенты", "color": "#ff4949"}
}, {
"id": 17,
"parent_id": null,
"responsible_id": null,
"type_id": 4,
"title": "Тестовая цель - 17",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 4, "title": "Персонал", "color": "#6190e8"}
}, {
"id": 19,
"parent_id": null,
"responsible_id": null,
"type_id": 4,
"title": "Тестовая цель - 19",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 4, "title": "Персонал", "color": "#6190e8"}
}, {
"id": 20,
"parent_id": 11,
"responsible_id": null,
"type_id": 2,
"title": "Тестовая цель - 20",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 2, "title": "Клиенты", "color": "#ff4949"}
}, {
"id": 21,
"parent_id": null,
"responsible_id": null,
"type_id": 3,
"title": "Тестовая цель - 21",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 3, "title": "Процессы", "color": "#13ce66"}
}, {
"id": 23,
"parent_id": null,
"responsible_id": null,
"type_id": 2,
"title": "Тестовая цель - 23",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 2, "title": "Клиенты", "color": "#ff4949"}
}, {
"id": 25,
"parent_id": null,
"responsible_id": null,
"type_id": 1,
"title": "Тестовая цель - 25",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 1, "title": "Финансы", "color": "#ffc82c"}
}, {
"id": 26,
"parent_id": 15,
"responsible_id": null,
"type_id": 2,
"title": "Тестовая цель - 26",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 2, "title": "Клиенты", "color": "#ff4949"}
}, {
"id": 27,
"parent_id": null,
"responsible_id": null,
"type_id": 1,
"title": "Тестовая цель - 27",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 1, "title": "Финансы", "color": "#ffc82c"}
}, {
"id": 28,
"parent_id": 7,
"responsible_id": null,
"type_id": 2,
"title": "Тестовая цель - 28",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 2, "title": "Клиенты", "color": "#ff4949"}
}, {
"id": 29,
"parent_id": null,
"responsible_id": null,
"type_id": 4,
"title": "Тестовая цель - 29",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 4, "title": "Персонал", "color": "#6190e8"}
}, {
"id": 31,
"parent_id": null,
"responsible_id": null,
"type_id": 2,
"title": "Тестовая цель - 31",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 2, "title": "Клиенты", "color": "#ff4949"}
}, {
"id": 33,
"parent_id": null,
"responsible_id": null,
"type_id": 3,
"title": "Тестовая цель - 33",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 3, "title": "Процессы", "color": "#13ce66"}
}, {
"id": 34,
"parent_id": 31,
"responsible_id": null,
"type_id": 4,
"title": "Тестовая цель - 34",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 4, "title": "Персонал", "color": "#6190e8"}
}, {
"id": 35,
"parent_id": null,
"responsible_id": null,
"type_id": 1,
"title": "Тестовая цель - 35",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 1, "title": "Финансы", "color": "#ffc82c"}
}, {
"id": 36,
"parent_id": 34,
"responsible_id": null,
"type_id": 1,
"title": "Тестовая цель - 36",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 1, "title": "Финансы", "color": "#ffc82c"}
}, {
"id": 37,
"parent_id": null,
"responsible_id": null,
"type_id": 4,
"title": "Тестовая цель - 37",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 4, "title": "Персонал", "color": "#6190e8"}
}, {
"id": 39,
"parent_id": null,
"responsible_id": null,
"type_id": 3,
"title": "Тестовая цель - 39",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 3, "title": "Процессы", "color": "#13ce66"}
}, {
"id": 40,
"parent_id": 34,
"responsible_id": null,
"type_id": 2,
"title": "Тестовая цель - 40",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 2, "title": "Клиенты", "color": "#ff4949"}
}]
I would use a recursive function to iterate through the tree and return the node when the expected one is found (I assumed the title is the search criteria) or return null if none was found.
In example :
var data = [
{
title: 'topNode',
id: 1,
children: [
{
title: 'node1',
id: 2,
children: [
{
title: 'randomNode_1',
id: 3,
},
{
title: 'node2',
id: 4,
children: [
{
title: 'randomNode_2',
id: 5,
children: [
{
title: 'node2',
id: 1111,
children: [
{
title: 'randomNode_3',
id: 1232,
}]
}]
}]
}]
}]
}];
function FindSpecificData(node, titleToFind)
{
let newNode = null;
for (let i = 0; i < node.length; ++i)
{
if (node[i].title == titleToFind)
newNode = node[i];
else if ('children' in node[i])
newNode = FindSpecificData(node[i].children, titleToFind);
if (newNode != null)
return (newNode);
}
return (null);
}
console.log(FindSpecificData(data, 'randomNode_2'));
console.log(FindSpecificData(data, 'randomNode_1'));
console.log(FindSpecificData(data, 'missing node'));
Try this simple method to find out your node
function getNode(node) {
if (node.title === 'randomNode_3') {
return true;
} else if (!node.children && !node.id) {
return false;
} else {
if (node.children) {
for (var i = 0; i < node.children.length; i++) {
getNode(node.children[i])
}
}
}
}
getNode(data[0])

Building a Dynamic Treant Chart

Good morning all,
I've been working on a small project to build a dynamic treant.js tree chart. To achieve this i have based my code on the collapsable example using the JSON method.
Unfortunately the JSON within the script isnt exactly perfect JSON which is making my life particularly difficult.
I have written a piece of script which creates the required JSON as a string which when I write to the window and copy into the collapsable.js the chart is drawn perfectly.
An example can be seen here;
{chart: {container: "#collapsable-example",animateOnInit: true,node: {collapsable: true},animation: {nodeAnimation: "easeOutBounce",nodeSpeed: 700,connectorsAnimation: "bounce",connectorsSpeed: 700}},nodeStructure: { "id": 1, "parent": 0, "text": { "name": "Tony Obrien", "Title": "Managing Director" }, "children": [ { "id": 2, "parent": 1, "text": { "name": "Tony Obrien", "Title": "Managing Director" }, "children": [ { "id": 4, "parent": 2, "text": { "name": "Tony Obrien", "Title": "Managing Director" }, "children": [] } ] }, { "id": 3, "parent": 1, "text": { "name": "Tony Obrien", "Title": "Managing Director" }, "children": [ { "id": 5, "parent": 3, "text": { "name": "Tony Obrien", "Title": "Managing Director" }, "children": [] } ] }, { "id": 6, "parent": 1, "text": { "name": "Tony Obrien", "Title": "Managing Director" }, "children": [] }, { "id": 7, "parent": 1, "text": { "name": "Tony Obrien", "Title": "Managing Director" }, "children": [] } ] }
what im struggling with is after I've built that string converting it to an object that treant.js likes.
for example
var chart_config = {chart: {container: "#collapsable-example",animateOnInit: true,node: {collapsable: true},animation: {nodeAnimation: "easeOutBounce",nodeSpeed: 700,connectorsAnimation: "bounce",connectorsSpeed: 700}},nodeStructure: { "id": 1, "parent": 0, "text": { "name": "Tony Obrien", "Title": "Managing Director" }, "children": [ { "id": 2, "parent": 1, "text": { "name": "Tony Obrien", "Title": "Managing Director" }, "children": [ { "id": 4, "parent": 2, "text": { "name": "Tony Obrien", "Title": "Managing Director" }, "children": [] } ] }, { "id": 3, "parent": 1, "text": { "name": "Tony Obrien", "Title": "Managing Director" }, "children": [ { "id": 5, "parent": 3, "text": { "name": "Tony Obrien", "Title": "Managing Director" }, "children": [] } ] }, { "id": 6, "parent": 1, "text": { "name": "Tony Obrien", "Title": "Managing Director" }, "children": [] }, { "id": 7, "parent": 1, "text": { "name": "Tony Obrien", "Title": "Managing Director" }, "children": [] } ] }
When the JSON is copied and pasted from the result of the code that generated it works absolutley fine but.....
var tree = eval({chart: {container: "#collapsable-example",animateOnInit: true,node: {collapsable: true},animation: {nodeAnimation: "easeOutBounce",nodeSpeed: 700,connectorsAnimation: "bounce",connectorsSpeed: 700}},nodeStructure: { "id": 1, "parent": 0, "text": { "name": "Tony Obrien", "Title": "Managing Director" }, "children": [ { "id": 2, "parent": 1, "text": { "name": "Tony Obrien", "Title": "Managing Director" }, "children": [ { "id": 4, "parent": 2, "text": { "name": "Tony Obrien", "Title": "Managing Director" }, "children": [] } ] }, { "id": 3, "parent": 1, "text": { "name": "Tony Obrien", "Title": "Managing Director" }, "children": [ { "id": 5, "parent": 3, "text": { "name": "Tony Obrien", "Title": "Managing Director" }, "children": [] } ] }, { "id": 6, "parent": 1, "text": { "name": "Tony Obrien", "Title": "Managing Director" }, "children": [] }, { "id": 7, "parent": 1, "text": { "name": "Tony Obrien", "Title": "Managing Director" }, "children": [] } ] })
chart_config = tree
This doesnt work. I get an unexpected token error. I have tried JSON.parse to no avail either. Does anyone have any ideas?
Your unexpected token error is likely from the eval call. Notice that it takes a string representing js code as an argument. You are giving it a js object, so the first '{' is likely the 'unexpected token'. Trying removing the eval wrapper and I bet it works.

How to implement Javascript logic in creating array with parents only has children

I am not very good at implementing logic, hence seeking your help to implement the following logic.
I have an js object array in parent child format in the following way:
"categories": {
"data": {
"1": {
"id": 1,
"name": "Churches & Religious Org.",
"description": "Church\/religious organization",
"parent": 267,
"icon": "home"
},
"2": {
"id": 2,
"name": "Bands & Musicians",
"description": "Musician\/band",
"parent": 259,
"icon": "music-note"
},
"3": {
"id": 3,
"name": "Products & Services",
"description": "Product\/service",
"parent": 260,
"icon": "cube"
},
"4": {
"id": 4,
"name": "Actors & Directors",
"description": "Actor\/director",
"parent": 256,
"icon": "film-marker"
},
"5": {
"id": 5,
"name": "Athletes & Players",
"description": "Athlete",
"parent": 264,
"icon": "ios-americanfootball"
},
"6": {
"id": 6,
"name": "Movies",
"description": "Movie",
"parent": 256,
"icon": "ios-film"
},
"7": {
"id": 7,
"name": "TV Shows",
"description": "TV show",
"parent": 256,
"icon": "ios-videocam"
},
"8": {
"id": 8,
"name": "Professional Teams",
"description": "Sports Team",
"parent": 264,
"icon": ""
},
"9": {
"id": 9,
"name": "Politicians",
"description": "Politician",
"parent": 263,
"icon": ""
},
"10": {
"id": 10,
"name": "Food Products",
"description": "Food & Beverage Company",
"parent": 258,
"icon": ""
}};
You can see from above that I have elements in array where there is parent_id field.
Now basically I wanted to have a function which taking this input, create the modified version of this array where I will have the list of only elements which have any number of children.
That is if any element has parent_id without any children then in the list that element will not be added.
As commented; your "array" is not an array. You can use Object.values to turn it into an array. Then map that to only take parent value.
Now now have an array with values that are the id's of an item's parent. You can use these id's to create a new object with reduce, assuming that your object has a key that is it's id {id:{id:id:...},otherid:{id:otherid,...},...
var data = {
"1": {
"id": 1,
"name": "Churches & Religious Org.",
"description": "Church\/religious organization",
"parent": 2,
"icon": "home"
},
"2": {//2 doesn't have a parent
"id": 2,
"name": "Bands & Musicians",
"description": "Musician\/band",
"icon": "music-note"
},
"3": {
"id": 3,
"name": "Products & Services",
"description": "Product\/service",
"parent": 1,
"icon": "cube"
}
};
console.log(
Object.values(data)
.map(d=>d.parent)//get only parent values
.filter(parent=>parent)//remove those that don't have parent
//reduce to a new object that only contains items that had other items
// with it's id as their parent
.reduce(
(result,item)=>{
result[item]=data[item];
return result;
},
{}
)
)
Elements which have children.
var obj = {
"categories": {
"data": {
"1": {
"id": 1,
"name": "Churches & Religious Org.",
"description": "Church\/religious organization",
"parent": 267,
"icon": "home"
},
"2": {
"id": 2,
"name": "Bands & Musicians",
"description": "Musician\/band",
"parent": 259,
"icon": "music-note"
},
"3": {
"id": 3,
"name": "Products & Services",
"description": "Product\/service",
"parent": 260,
"icon": "cube"
},
"4": {
"id": 4,
"name": "Actors & Directors",
"description": "Actor\/director",
"parent": 256,
"icon": "film-marker"
},
"5": {
"id": 5,
"name": "Athletes & Players",
"description": "Athlete",
"parent": 264,
"icon": "ios-americanfootball"
},
"6": {
"id": 6,
"name": "Movies",
"description": "Movie",
"parent": 256,
"icon": "ios-film"
},
"7": {
"id": 7,
"name": "TV Shows",
"description": "TV show",
"parent": 256,
"icon": "ios-videocam"
},
"8": {
"id": 8,
"name": "Professional Teams",
"description": "Sports Team",
"parent": 264,
"icon": ""
},
"9": {
"id": 9,
"name": "Politicians",
"description": "Politician",
"parent": 263,
"icon": ""
},
"10": {
"id": 10,
"name": "Food Products",
"description": "Food & Beverage Company",
"parent": 258,
"icon": ""
}
}
}
}
var elemetsWithChildren = [];
for (var propt in obj.categories.data) {
if (elemetsWithChildren.indexOf(obj.categories.data[propt].parent) == -1) {
elemetsWithChildren.push(obj.categories.data[propt].parent);
}
}
console.log(elemetsWithChildren);
With this, you have an object with elements and numbers of children
var elemetsWithChildren = {};
for(var propt in obj.categories.data){
let parent = obj.categories.data[propt].parent
if(!elemetsWithChildren.hasOwnProperty(parent)){
elemetsWithChildren[parent] = 1;
}else{
elemetsWithChildren[parent]++;
}
}
console.log(elemetsWithChildren);

Nested JSON parsing using JSONparse()

I cannot seem to extract the data I want from this (verified) JSON string coming from my home automation server (i.e. I cannot change the JSON return).
var myJson = '{ "Device_Num_6": { "states": [ { "id": 207, "service": "urn:upnp-org:serviceId:SwitchPower1", "variable": "Status", "value": "0" }, { "id": 208, "service": "urn:upnp-org:serviceId:Dimming1", "variable": "LoadLevelTarget", "value": "94" }, { "id": 209, "service": "urn:upnp-org:serviceId:Dimming1", "variable": "LoadLevelStatus", "value": "0" }, { "id": 210, "service": "urn:micasaverde-com:serviceId:HaDevice1", "variable": "Configured", "value": "1" }, { "id": 211, "service": "urn:micasaverde-com:serviceId:HaDevice1", "variable": "ModeSetting", "value": "1:;2:;3:;4:" }, { "id": 212, "service": "urn:micasaverde-com:serviceId:HaDevice1", "variable": "LastUpdate", "value": "1438440091" }, { "id": 213, "service": "urn:micasaverde-com:serviceId:HaDevice1", "variable": "FirstConfigured", "value": "1438440091" }, { "id": 214, "service": "urn:micasaverde-com:serviceId:ZWaveDevice1", "variable": "Capabilities", "value": "209,140,0,4,17,1,L,R,RS,|38:1,39,112,114,115,134," }, { "id": 215, "service": "urn:micasaverde-com:serviceId:ZWaveDevice1", "variable": "ManufacturerInfo", "value": "99,17495,12848" }, { "id": 216, "service": "urn:micasaverde-com:serviceId:ZWaveDevice1", "variable": "VersionInfo", "value": "6,1,91,2,11" }, { "id": 217, "service": "urn:micasaverde-com:serviceId:ZWaveDevice1", "variable": "NodeInfo", "value": "26,27,70,72,73,86," }, { "id": 218, "service": "urn:micasaverde-com:serviceId:ZWaveDevice1", "variable": "Neighbors", "value": "1,2,3,4,6,7,8,9,11,12,13,14,15,16,17,21,25,26,27,31,32,33,34,35," }, { "id": 219, "service": "urn:micasaverde-com:serviceId:ZWaveDevice1", "variable": "LastReset", "value": "0" }, { "id": 220, "service": "urn:micasaverde-com:serviceId:ZWaveDevice1", "variable": "AssociationNum", "value": "0" }, { "id": 221, "service": "urn:micasaverde-com:serviceId:ZWaveDevice1", "variable": "LastRouteUpdate", "value": "1468760253" }, { "id": 222, "service": "urn:micasaverde-com:serviceId:ZWaveDevice1", "variable": "PollOk", "value": "43947" }, { "id": 223, "service": "urn:micasaverde-com:serviceId:ZWaveDevice1", "variable": "LastNnu", "value": "1468735200,700" }, { "id": 224, "service": "urn:micasaverde-com:serviceId:ZWaveDevice1", "variable": "LastArr", "value": "1468735200,700" }, { "id": 225, "service": "urn:micasaverde-com:serviceId:ZWaveDevice1", "variable": "PollNoReply", "value": "54" }, { "id": 226, "service": "urn:micasaverde-com:serviceId:ZWaveNetwork1", "variable": "ConsecutivePollFails", "value": "0" } ], "Jobs": [ ], "PendingJobs": 0, "tooltip": { "display": 0 }, "status": -1 }, "Using_2G": 0, "LoadTime": 1468766261, "DataVersion": 766262647, "UserData_DataVersion": 766261013, "TimeStamp": 1468779944, "lights_on": 3, "lights_off": 8, "doors_locked": 5, "doors_unlocked": 2, "sensors_tripped": 0, "sensors_not_tripped": 8, "failed_devices": 8, "visible_devices": 93, "partitions_active": 0, "partitions_notactive": 2, "alerts": [ { "PK_Device": 154, "Room": 10, "DeviceName": "Laundry Door Lock", "DeviceType": "urn:schemas-micasaverde-com:device:DoorLock:1", "PK_Alert": "4742240051", "LocalDate": "2016-07-17 10:38:22", "EventType": 4, "SourceType": 4, "Argument": 0, "Filesize": 0, "Severity": 2, "LocalTimestamp": 1468766302, "Code": "SL_BATTERYALARM", "NewValue": "0", "Description": "Laundry Door Lock", "Users": "", "Server_Storage": "", "Key": "", "Icon": "", "PK_Store": "0" }, { "PK_Device": 150, "Room": 23, "DeviceName": "Kids Bath Motion", "DeviceType": "urn:schemas-micasaverde-com:device:MotionSensor:1", "PK_Alert": "4742240181", "LocalDate": "2016-07-17 10:38:22", "EventType": 4, "SourceType": 4, "Argument": 0, "Filesize": 0, "Severity": 2, "LocalTimestamp": 1468766302, "Code": "SL_BATTERYALARM", "NewValue": "10", "Description": "Kids Bath Motion", "Users": "", "Server_Storage": "", "Key": "", "Icon": "", "PK_Store": "0" }, { "PK_Device": 101, "Room": 21, "DeviceName": "Cabana Door Lock", "DeviceType": "urn:schemas-micasaverde-com:device:DoorLock:1", "PK_Alert": "4742255081", "LocalDate": "2016-07-17 10:40:18", "EventType": 4, "SourceType": 4, "Argument": 0, "Filesize": 0, "Severity": 2, "LocalTimestamp": 1468766418, "Code": "DL_LOW_BATTERY", "NewValue": "1", "Description": "Cabana Door Lock", "Users": "", "Server_Storage": "", "Key": "", "Icon": "", "PK_Store": "0" }, { "PK_Device": 101, "Room": 21, "DeviceName": "Cabana Door Lock", "DeviceType": "urn:schemas-micasaverde-com:device:DoorLock:1", "PK_Alert": "4742255231", "LocalDate": "2016-07-17 10:40:18", "EventType": 4, "SourceType": 4, "Argument": 0, "Filesize": 0, "Severity": 3, "LocalTimestamp": 1468766418, "Code": "DL_LOCK_CHANGED", "NewValue": "3", "Description": "Cabana Door Lock", "Users": "", "Server_Storage": "", "Key": "", "Icon": "", "PK_Store": "0" }, { "PK_Device": 101, "Room": 21, "DeviceName": "Cabana Door Lock", "DeviceType": "urn:schemas-micasaverde-com:device:DoorLock:1", "PK_Alert": "4742255371", "LocalDate": "2016-07-17 10:40:18", "EventType": 4, "SourceType": 4, "Argument": 0, "Filesize": 0, "Severity": 3, "LocalTimestamp": 1468766418, "Code": "DL_CODE_CHANGED", "NewValue": "3", "Description": "Cabana Door Lock", "Users": "", "Server_Storage": "", "Key": "", "Icon": "", "PK_Store": "0" }, { "PK_Device": 101, "Room": 21, "DeviceName": "Cabana Door Lock", "DeviceType": "urn:schemas-micasaverde-com:device:DoorLock:1", "PK_Alert": "4742255471", "LocalDate": "2016-07-17 10:40:18", "EventType": 4, "SourceType": 4, "Argument": 0, "Filesize": 0, "Severity": 3, "LocalTimestamp": 1468766418, "Code": "DL_USERCODE", "NewValue": "UserID=\"1\" UserName=\"Main\"", "Description": "Cabana Door Lock", "Users": "", "Server_Storage": "", "Key": "", "Icon": "", "PK_Store": "0" }, { "PK_Device": 101, "Room": 21, "DeviceName": "Cabana Door Lock", "DeviceType": "urn:schemas-micasaverde-com:device:DoorLock:1", "PK_Alert": "4742255591", "LocalDate": "2016-07-17 10:40:18", "EventType": 4, "SourceType": 4, "Argument": 0, "Filesize": 0, "Severity": 3, "LocalTimestamp": 1468766418, "Code": "DL_LOCK_BUTTON", "NewValue": "1", "Description": "Cabana Door Lock", "Users": "", "Server_Storage": "", "Key": "", "Icon": "", "PK_Store": "0" }, { "PK_Device": 101, "Room": 21, "DeviceName": "Cabana Door Lock", "DeviceType": "urn:schemas-micasaverde-com:device:DoorLock:1", "PK_Alert": "4742255721", "LocalDate": "2016-07-17 10:40:18", "EventType": 4, "SourceType": 4, "Argument": 0, "Filesize": 0, "Severity": 1, "LocalTimestamp": 1468766418, "Code": "DL_LOCK_FAILURE", "NewValue": "1", "Description": "Cabana Door Lock", "Users": "", "Server_Storage": "", "Key": "", "Icon": "", "PK_Store": "0" }, { "PK_Device": 101, "Room": 21, "DeviceName": "Cabana Door Lock", "DeviceType": "urn:schemas-micasaverde-com:device:DoorLock:1", "PK_Alert": "4742255801", "LocalDate": "2016-07-17 10:40:18", "EventType": 4, "SourceType": 4, "Argument": 0, "Filesize": 0, "Severity": 1, "LocalTimestamp": 1468766418, "Code": "DL_PINFAILED", "NewValue": "1", "Description": "Cabana Door Lock", "Users": "", "Server_Storage": "", "Key": "", "Icon": "", "PK_Store": "0" }, { "PK_Device": 101, "Room": 21, "DeviceName": "Cabana Door Lock", "DeviceType": "urn:schemas-micasaverde-com:device:DoorLock:1", "PK_Alert": "4742255971", "LocalDate": "2016-07-17 10:40:18", "EventType": 4, "SourceType": 4, "Argument": 0, "Filesize": 0, "Severity": 2, "LocalTimestamp": 1468766418, "Code": "SL_BATTERYALARM", "NewValue": "0", "Description": "Cabana Door Lock", "Users": "", "Server_Storage": "", "Key": "", "Icon": "", "PK_Store": "0" } ], "ZWaveStatus": 1, "Mode": 1, "LocalTime": "2016-07-17 14:25:44 D" }';
var myObject = JSON.parse(myJson);
console.log(myObject.Device_Num_6.states[0].id); // should return 207
Your json has invalid format. Because of that you couldn't to parse it as JSON.parse method. Try to check it here http://jsonviewer.stack.hu/
UPD: issue with this string "NewValue": "UserID=\"1\" UserName=\"Main\"". You should make it as "NewValue": "UserID=\\"1\\" UserName=\\"Main\\""

How to loop inside a json file with javascript?

I have a json file returned on my javascript code. The file looks like this :
{
"data": [
{
"id": "594984240522886",
"from": {
"id": "593959083958735",
"category": "Community",
"name": "Decoc"
},
"name": "Ducks",
"description": "ducks",
"link": "http://www.facebook.com/album.php?fbid=594984240522886&id=593959083958735&aid=1073741834",
"cover_photo": "594984260522884",
"count": 4,
"type": "normal",
"created_time": "2013-06-13T15:12:22+0000",
"updated_time": "2013-06-13T15:12:40+0000",
"can_upload": false
},
{
"id": "593963787291598",
"from": {
"id": "593959083958735",
"category": "Community",
"name": "Decoc"
},
"name": "Profile Pictures",
"link": "http://www.facebook.com/album.php?fbid=593963787291598&id=593959083958735&aid=1073741832",
"cover_photo": "593963797291597",
"count": 1,
"type": "profile",
"created_time": "2013-06-11T16:52:29+0000",
"updated_time": "2013-06-11T16:52:31+0000",
"can_upload": false
},
{
"id": "593963467291630",
"from": {
"id": "593959083958735",
"category": "Community",
"name": "Decoc"
},
"name": "Goats",
"description": "goats",
"link": "http://www.facebook.com/album.php?fbid=593963467291630&id=593959083958735&aid=1073741831",
"cover_photo": "593963477291629",
"count": 7,
"type": "normal",
"created_time": "2013-06-11T16:51:56+0000",
"updated_time": "2013-06-11T16:52:02+0000",
"can_upload": false
},
{
"id": "593962700625040",
"from": {
"id": "593959083958735",
"category": "Community",
"name": "Decoc"
},
"name": "Dogs",
"description": "dogs",
"link": "http://www.facebook.com/album.php?fbid=593962700625040&id=593959083958735&aid=1073741830",
"cover_photo": "593962710625039",
"count": 10,
"type": "normal",
"created_time": "2013-06-11T16:50:27+0000",
"updated_time": "2013-06-11T16:50:37+0000",
"can_upload": false
},
{
"id": "593961937291783",
"from": {
"id": "593959083958735",
"category": "Community",
"name": "Decoc"
},
"name": "Cows",
"description": "Cows",
"link": "http://www.facebook.com/album.php?fbid=593961937291783&id=593959083958735&aid=1073741829",
"cover_photo": "593961983958445",
"count": 5,
"type": "normal",
"created_time": "2013-06-11T16:48:26+0000",
"updated_time": "2013-06-11T16:49:32+0000",
"can_upload": false
}
],
"paging": {
"cursors": {
"after": "NTkzOTYxOTM3MjkxNzgz",
"before": "NTk0OTg0MjQwNTIyODg2"
}
}
}
I would like to loop inside the "data" and see how many different data elements exist(as you see each element has an id , from , name , description..) . How can i do that with javascript?
You can try the following code:
for(i=0;json.data.length;i++){
var element = json.data[i];
}
or also in this other way:
for (i in json.data) {
if (json.data.hasOwnProperty(i)) {
var element = json.data[i];
}
}

Categories