Hi I am using JavaScript and jQuery as client side script. I am little bit new to Recursive functions. I have a JSON data as below and I have tried to make a tree structure using below JSON data by writing a recursive function but I am not able to build the tree structure.
var jsonData = { "$id": "45", "_children": [{ "$id": "46", "_children": [{ "$id": "47", "_children": [{ "$id": "48", "_children": [{ "$id": "49", "_children": null, "id": "Test1", "text": "Text1", "name": "name1", "parent": null, "root": { "$ref": "49" }, "depth": 0, "children": [] }], "id": "id1", "text": "text2", "name": "name2", "parent": null, "root": { "$ref": "48" }, "depth": 0, "children": [{ "$ref": "49" }] }], "id": "id3", "text": "text4", "name": "name4", "parent": null, "root": { "$ref": "47" }, "depth": 0, "children": [{ "$ref": "48" }] }, { "$id": "50", "_children": [{ "$id": "51", "_children": [{ "$id": "52", "_children": null, "id": "id6", "text": "text6", "name": "name6", "parent": null, "root": { "$ref": "52" }, "depth": 0, "children": [] }], "id": "id7", "text": "text7", "name": "name7", "parent": null, "root": { "$ref": "51" }, "depth": 0, "children": [{ "$ref": "52" }] }], "id": "id8", "text": "text8", "name": "name8", "parent": null, "root": { "$ref": "50" }, "depth": 0, "children": [{ "$ref": "51" }] }], "id": "id9", "text": "text9", "name": "name9", "parent": null, "root": { "$ref": "46" }, "depth": 0, "children": [{ "$ref": "47" }, { "$ref": "50" }] }, { "$id": "53", "_children": [{ "$id": "54", "_children": null, "id": "id10", "text": "text10", "name": "name10", "parent": null, "root": { "$ref": "54" }, "depth": 0, "children": [] }], "id": "id11", "text": "text11", "name": "name11", "parent": null, "root": { "$ref": "53" }, "depth": 0, "children": [{ "$ref": "54" }] }], "id": "0", "text": "0", "name": "", "parent": null, "root": { "$ref": "45" }, "depth": 0, "children": [{ "$ref": "46" }, { "$ref": "53" }] }
Required Output:
var treeNode = {
id: 101, // random
text: object.name,
icon: "fas fa-plus",
subNode: {
// id, text, icon and subNode of Children object
// recursive data, So on....
}
};
Can anyone suggest me or help me to write javascript or jQuery Recursive function based on above JSON data so I can build tree structure. I know I am asking about help because I do have less knowledge about recursive function.
If we abstract this a bit, it's pretty easy to write a general-purpose tree-mapping function. Then we can supply two callback functions: one to find the child nodes of the input and one to build the output node based on the input and the mapped children. Such a function turns out to be surprisingly simple:
const mapTree = (getChildren, transformNode) => (tree) =>
transformNode (
tree,
(getChildren (tree) || []) .map (mapTree (getChildren, transformNode))
)
For your data, getChildren is simply (node) => node._children
And the node transformation might be as simple as:
const transformNode = (node, children) =>
({
id: node.$id, // or a randomizing call?
text: node.name,
icon: "fas fa-plus", // is this really a fixed value?
subNode: children
})
Putting this together we get
const mapTree = (getChildren, transformNode) => (tree) =>
transformNode (
tree,
(getChildren (tree) || []) .map (mapTree (getChildren, transformNode))
)
const kids = (node) => node._children
const transformNode = (node, children) =>
({
id: node.$id,
text: node.name,
icon: "fas fa-plus",
subNode: children
})
const myTransform = mapTree (kids, transformNode)
const jsonData = { "$id": "45", "_children": [{ "$id": "46", "_children": [{ "$id": "47", "_children": [{ "$id": "48", "_children": [{ "$id": "49", "_children": null, "id": "Test1", "text": "Text1", "name": "name1", "parent": null, "root": { "$ref": "49" }, "depth": 0, "children": [] }], "id": "id1", "text": "text2", "name": "name2", "parent": null, "root": { "$ref": "48" }, "depth": 0, "children": [{ "$ref": "49" }] }], "id": "id3", "text": "text4", "name": "name4", "parent": null, "root": { "$ref": "47" }, "depth": 0, "children": [{ "$ref": "48" }] }, { "$id": "50", "_children": [{ "$id": "51", "_children": [{ "$id": "52", "_children": null, "id": "id6", "text": "text6", "name": "name6", "parent": null, "root": { "$ref": "52" }, "depth": 0, "children": [] }], "id": "id7", "text": "text7", "name": "name7", "parent": null, "root": { "$ref": "51" }, "depth": 0, "children": [{ "$ref": "52" }] }], "id": "id8", "text": "text8", "name": "name8", "parent": null, "root": { "$ref": "50" }, "depth": 0, "children": [{ "$ref": "51" }] }], "id": "id9", "text": "text9", "name": "name9", "parent": null, "root": { "$ref": "46" }, "depth": 0, "children": [{ "$ref": "47" }, { "$ref": "50" }] }, { "$id": "53", "_children": [{ "$id": "54", "_children": null, "id": "id10", "text": "text10", "name": "name10", "parent": null, "root": { "$ref": "54" }, "depth": 0, "children": [] }], "id": "id11", "text": "text11", "name": "name11", "parent": null, "root": { "$ref": "53" }, "depth": 0, "children": [{ "$ref": "54" }] }], "id": "0", "text": "0", "name": "", "parent": null, "root": { "$ref": "45" }, "depth": 0, "children": [{ "$ref": "46" }, { "$ref": "53" }] }
console .log (myTransform (jsonData))
This does something slightly different from your requested output. You had written subNode: { ... }, but instead I'm returning an array of objects, subNodes: [ ... ], as I don't make any real sense of a plain object here.
Also, this will yield an empty subNodes array if an input node has no children. If you would rather not have the subNodes property, you could replace
subNode: children
with something like
...(children .length ? {subNode: children} : {})
Obviously, you don't need the named helpers and could call mapTree with anonymous functions like this:
const myTransform = mapTree (
(node) => node._children,
(node, children) =>
({
id: node.$id,
text: node.name,
icon: "fas fa-plus",
subNode: children
})
)
This mapTree function was very easy to write, as I didn't have to think about any details of the output or input formats as I wrote it. But perhaps that abstraction is not helpful to me, and I'm never going to use it except here. If so, I can simply rework the abstract version by plugging the hard-coded callbacks directly. With only a little manipulation, that will turn it into this version:
const newTransform = (node) =>
({
id: node.$id,
text: node.name,
icon: "fas fa-plus",
subNode: (node._children || []).map(newTransform)
})
const jsonData = { "$id": "45", "_children": [{ "$id": "46", "_children": [{ "$id": "47", "_children": [{ "$id": "48", "_children": [{ "$id": "49", "_children": null, "id": "Test1", "text": "Text1", "name": "name1", "parent": null, "root": { "$ref": "49" }, "depth": 0, "children": [] }], "id": "id1", "text": "text2", "name": "name2", "parent": null, "root": { "$ref": "48" }, "depth": 0, "children": [{ "$ref": "49" }] }], "id": "id3", "text": "text4", "name": "name4", "parent": null, "root": { "$ref": "47" }, "depth": 0, "children": [{ "$ref": "48" }] }, { "$id": "50", "_children": [{ "$id": "51", "_children": [{ "$id": "52", "_children": null, "id": "id6", "text": "text6", "name": "name6", "parent": null, "root": { "$ref": "52" }, "depth": 0, "children": [] }], "id": "id7", "text": "text7", "name": "name7", "parent": null, "root": { "$ref": "51" }, "depth": 0, "children": [{ "$ref": "52" }] }], "id": "id8", "text": "text8", "name": "name8", "parent": null, "root": { "$ref": "50" }, "depth": 0, "children": [{ "$ref": "51" }] }], "id": "id9", "text": "text9", "name": "name9", "parent": null, "root": { "$ref": "46" }, "depth": 0, "children": [{ "$ref": "47" }, { "$ref": "50" }] }, { "$id": "53", "_children": [{ "$id": "54", "_children": null, "id": "id10", "text": "text10", "name": "name10", "parent": null, "root": { "$ref": "54" }, "depth": 0, "children": [] }], "id": "id11", "text": "text11", "name": "name11", "parent": null, "root": { "$ref": "53" }, "depth": 0, "children": [{ "$ref": "54" }] }], "id": "0", "text": "0", "name": "", "parent": null, "root": { "$ref": "45" }, "depth": 0, "children": [{ "$ref": "46" }, { "$ref": "53" }] }
console .log (newTransform (jsonData))
There's an important point here. This generic function was much easier to write than if I'd tried to write something to convert your format directly. While there is a danger in too-early abstraction, it also can offer significant benefits. I might well choose to keep only that last version, but the generic abstraction simplified the development of it.
It can be something like that, with using the json data model
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="lib/style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div id="myDiv"></div>
</body>
<script>
var treeData={
"Id":"10",
"text":"Document Categories",
"icon":"fas fa-plus",
"subNode":
[
{
"Id":"11",
"text":"Pdf Documents",
"icon":"fas fa-plus",
"subNode":[
{
"Id":"31",
"text":"Book Pdfs",
"icon":"fas fa-plus",
"subNode":[]
},
{
"Id":"32",
"text":"EPub",
"icon":"fas fa-plus",
"subNode":[
{
"Id":"20",
"text":"EBook Epubs1",
"icon":"fas fa-plus",
"subNode":[]
},
{
"Id":"30",
"text":"EBook Epubs2",
"icon":"fas fa-plus",
"subNode":[]
}
]
}
]
},
{
"Id":"33",
"text":"Text Documents",
"icon":"fas fa-plus",
"subNode":[
{
"Id":"32",
"text":"Book Text",
"icon":"fas fa-plus",
"subNode":[]
},
{
"Id":"35",
"text":"Automatic Text",
"icon":"fas fa-plus",
"subNode":[]
}
]
}
]
};
var newTree = AddRecursive(null, treeData);
var treeDiv = $('#myDiv');
treeDiv.append(newTree);
function AddRecursive(tree, data) {
if (tree == null) {
tree = $('<ul/>');
tree.attr('id', 'treeID');
}
var listU = $('<ul />');
listU.addClass('ul class');
var listItem = $('<li />');
listItem.addClass('li class');
listItem.attr('data-id', data.Id);
var link = $('<a />');
var i = $('<i/>').addClass('fa fa-folder');
link.append(i);
//link.addClass("linkClass");
link.append(data.text);
listItem.append(link);
if (data.subNode.length > 0) {
var span = $(' <span />');
span.addClass('fa-chevron-down');
link.append(span);
}
listU.append(listItem);
tree.append(listU);
for (i in data.subNode) {
AddRecursive(listItem, data.subNode[i]);
}
return tree;
}
</script>
</html>
Related
I'm manipulating some javascript objects and I want to know if is there a more efficient and easy way to process my data.
I already do that, but I'm a beginner in js.
I have four objects with this structure: basically there is an array of blocks and any object has a different number of blocks. In every block, in the features attribute, I have another array with some features.
Then I have another object, and I have to remove from this object (I call it structure) blocks and features that are not present in my four initial object.
This is a sample product object
[
{
"ID": 16293,
"SortNo": "20",
"FeatureGroup": {
"ID": "148",
"Name": {
"Value": "Design",
"Language": "IT"
}
},
"Features": [
{
"Localized": 0,
"ID": "155744521",
"Type": "dropdown",
"Value": "Round",
"CategoryFeatureId": "85327",
"CategoryFeatureGroupID": "16293",
"SortNo": "155",
"PresentationValue": "Rotondo",
"RawValue": "Round",
"LocalValue": [],
"Description": "The external form",
"Mandatory": "1",
"Searchable": "0",
"Feature": {
"ID": "9397",
"Sign": "",
"Measure": {
"ID": "29",
"Sign": "",
"Signs": {
"ID": "",
"_": "",
"Language": "IT"
}
},
"Name": {
"Value": "Forma",
"Language": "IT"
}
}
},
{
"Localized": 0,
"ID": "155655523",
"Type": "multi_dropdown",
"Value": "White",
"CategoryFeatureId": "85298",
"CategoryFeatureGroupID": "16293",
"SortNo": "90",
"PresentationValue": "Bianco",
"RawValue": "White",
"LocalValue": [],
"Description": "The colour of the housing",
"Mandatory": "1",
"Searchable": "1",
"Feature": {
"ID": "10059",
"Sign": "",
"Measure": {
"ID": "29",
"Sign": "",
"Signs": {
"ID": "",
"_": "",
"Language": "IT"
}
},
"Name": {
"Value": "Colore struttura",
"Language": "IT"
}
}
},
{
"Localized": 0,
"ID": "155655525",
"Type": "multi_dropdown",
"Value": "White",
"CategoryFeatureId": "85301",
"CategoryFeatureGroupID": "16293",
"SortNo": "80",
"PresentationValue": "Bianco",
"RawValue": "White",
"LocalValue": [],
"Description": "The colour of the band",
"Mandatory": "1",
"Searchable": "1",
"Feature": {
"ID": "11025",
"Sign": "",
"Measure": {
"ID": "29",
"Sign": "",
"Signs": {
"ID": "",
"_": "",
"Language": "IT"
}
},
"Name": {
"Value": "Colore cinturino",
"Language": "IT"
}
}
},
{
"Localized": 0,
"ID": "219617494",
"Type": "y_n",
"Value": "Y",
"CategoryFeatureId": "168947",
"CategoryFeatureGroupID": "16293",
"SortNo": "-6",
"PresentationValue": "Sì",
"RawValue": "Y",
"LocalValue": [],
"Description": "The product is protected from water",
"Mandatory": "0",
"Searchable": "0",
"Feature": {
"ID": "7509",
"Sign": "",
"Measure": {
"ID": "26",
"Sign": "",
"Signs": {
"ID": "",
"_": "",
"Language": "IT"
}
},
"Name": {
"Value": "Resistente all'acqua",
"Language": "IT"
}
}
}
]
},
{
"ID": 34567,
"SortNo": "20",
"FeatureGroup": {
"ID": "184",
"Name": {
"Value": "Prestazione",
"Language": "IT"
}
},
"Features": [
{
"Localized": 0,
"ID": "155744528",
"Type": "y_n",
"Value": "N",
"CategoryFeatureId": "94697",
"CategoryFeatureGroupID": "34567",
"SortNo": "800",
"PresentationValue": "No",
"RawValue": "N",
"LocalValue": [],
"Description": "La Frequenza modulare radio produce la miglior recezione di qualsiasi canale radio. Quando viene usato un auricolare, produce un effetto di suono da stereo r",
"Mandatory": "1",
"Searchable": "0",
"Feature": {
"ID": "2172",
"Sign": "",
"Measure": {
"ID": "26",
"Sign": "",
"Signs": {
"ID": "",
"_": "",
"Language": "IT"
}
},
"Name": {
"Value": "Radio FM",
"Language": "IT"
}
}
},
{
"Localized": 0,
"ID": "155744530",
"Type": "multi_dropdown",
"Value": "Not supported",
"CategoryFeatureId": "85357",
"CategoryFeatureGroupID": "34567",
"SortNo": "500",
"PresentationValue": "Non supportato",
"RawValue": "Not supported",
"LocalValue": [],
"Description": "Types of memory cards which can be used with this product.",
"Mandatory": "1",
"Searchable": "0",
"Feature": {
"ID": "730",
"Sign": "",
"Measure": {
"ID": "29",
"Sign": "",
"Signs": {
"ID": "",
"_": "",
"Language": "IT"
}
},
"Name": {
"Value": "Tipi schede di memoria",
"Language": "IT"
}
}
}
]
}
]
Here i loop my initial objects (this.compare_products) to extract, in two arrays (featureGroupIds - featureIds) the ID of my block and the CategoryFeatureId
let featureGroupIds = []
let featureIds = []
this.compare_products.forEach((object) => {
featureGroupIds = featureGroupIds.concat(FeaturesGroups.map(o => o.ID))
featureIds = featureIds.concat(FeaturesGroups.map(o => o.Features.map(o => o. CategoryFeatureId))).flat(2)
})
The two arrays, featureGroupIds and featureIds are now filled with every block ID and every CategoryFeatureId present in my four object.
Now I have to filter the object I call "structure" to remove the block and the features with an ID that is not present in my arrays.
This is my structure, and as you can see is similar.
[
{
"name": "Display",
"data": {
"id": 34566,
"category_id": 2647
},
"features": [
{
"name": "Tipo di display",
"data": {
"id": 85325,
"category_id": 2647,
"feature_id": 9104,
"category_feature_group_id": 34566,
"order": 10100140
}
},
{
"name": "Touch screen",
"data": {
"id": 85331,
"category_id": 2647,
"feature_id": 4963,
"category_feature_group_id": 34566,
"order": 10100129
}
},
{
"name": "Dimensioni schermo",
"data": {
"id": 158002,
"category_id": 2647,
"feature_id": 3544,
"category_feature_group_id": 34566,
"order": 100149
}
},
{
"name": "à di Pixel",
"data": {
"id": 85347,
"category_id": 2647,
"feature_id": 13246,
"category_feature_group_id": 34566,
"order": 100147
}
},
{
"name": "Tipo di vetro",
"data": {
"id": 94704,
"category_id": 2647,
"feature_id": 7610,
"category_feature_group_id": 34566,
"order": 100050
}
}
]
},
{
"name": "Altre caratteristiche",
"data": {
"id": 34569,
"category_id": 2647,
"feature_group_id": 146,
"name": null,
"order": 0
},
"features": [
{
"name": "inside",
"data": {
"id": 110410,
"category_id": 2647,
"feature_id": 18688,
"category_feature_group_id": 34569,
"order": 100000
}
}
]
}
]
Here is my function
structure = structure.filter(featureGroup => this.featureGroupIds.includes(featureGroup.data.id));
structure.map((object) => {
object.features.filter(feature => this.featureIds.includes(feature.data.feature_id))
})
this.featureIds and this.featureGroupIds are the array with the group IDS and with the feature IDS.
Is there a more efficient way to do this?
This question already has answers here:
Sort nested array of object in javascript
(4 answers)
Closed 3 years ago.
I have this kind of array with objects. In each object except properties i have another array with objects called "secondary_fields". I need to access the last element in the secondary_fields array (secondary_fields[3]) where i have value of when it is created and after that to sort all of the objects
by the date time based on the value inside for example "2020-01-13 17:42:51";
But not with ES6 because i am using old platform where the ES6 version of Java Script is not supported
let arr =
[
{
"external": false,
"link": "--",
"direct": false,
"display_field": "new best article",
"id": "kb_knowledge:33",
"secondary_fields": [
{
"display_value": "Test Admin",
"name": "author",
"label": "Author",
"type": "reference",
"value": "xx"
},
{
"display_value": "25",
"name": "sys_view_count",
"label": "View count",
"type": "integer",
"value": "25"
},
{
"display_value": "2020-01-13 09:44:54",
"name": "sys_updated_on",
"label": "Updated",
"type": "glide_date_time",
"value": "2020-01-13 17:44:54"
},
{
"display_value": "2020-01-13 09:42:51",
"name": "sys_created_on",
"label": "Created",
"type": "glide_date_time",
"value": "2020-01-13 17:42:51"
}
],
},
{
"external": false,
"link": "--",
"direct": false,
"display_field": "How to connect the iPod to Wi-Fi",
"id": "kb_knowledge:11",
"secondary_fields": [
{
"display_value": "John",
"name": "author",
"label": "Author",
"type": "reference",
"value": "xxnnx"
},
{
"display_value": "16",
"name": "sys_view_count",
"label": "View count",
"type": "integer",
"value": "16"
},
{
"display_value": "2019-12-18 08:18:08",
"name": "sys_updated_on",
"label": "Updated",
"type": "glide_date_time",
"value": "2019-12-18 16:18:08"
},
{
"display_value": "2019-10-21 12:27:22",
"name": "sys_created_on",
"label": "Created",
"type": "glide_date_time",
"value": "2019-10-21 19:27:22"
}
],
}
]
You can make use of the array method's sort method and sort on display_value.
arr.sort(function(a, b) {
return new Date(a.secondary_fields[3].display_value) - new Date(b.secondary_fields[3].display_value)
})
Edit
Or I guess in your case,
return new Date(b.secondary_fields[3].display_value) - new Date(a.secondary_fields[3].display_value)
let arr =
[
{
"external": false,
"link": "--",
"direct": false,
"display_field": "new best article",
"id": "kb_knowledge:33",
"secondary_fields": [
{
"display_value": "Test Admin",
"name": "author",
"label": "Author",
"type": "reference",
"value": "xx"
},
{
"display_value": "25",
"name": "sys_view_count",
"label": "View count",
"type": "integer",
"value": "25"
},
{
"display_value": "2020-01-13 09:44:54",
"name": "sys_updated_on",
"label": "Updated",
"type": "glide_date_time",
"value": "2020-01-13 17:44:54"
},
{
"display_value": "2020-01-13 09:42:51",
"name": "sys_created_on",
"label": "Created",
"type": "glide_date_time",
"value": "2020-01-13 17:42:51"
}
],
},
{
"external": false,
"link": "--",
"direct": false,
"display_field": "How to connect the iPod to Wi-Fi",
"id": "kb_knowledge:11",
"secondary_fields": [
{
"display_value": "John",
"name": "author",
"label": "Author",
"type": "reference",
"value": "xxnnx"
},
{
"display_value": "16",
"name": "sys_view_count",
"label": "View count",
"type": "integer",
"value": "16"
},
{
"display_value": "2019-12-18 08:18:08",
"name": "sys_updated_on",
"label": "Updated",
"type": "glide_date_time",
"value": "2019-12-18 16:18:08"
},
{
"display_value": "2019-10-21 12:27:22",
"name": "sys_created_on",
"label": "Created",
"type": "glide_date_time",
"value": "2019-10-21 19:27:22"
}
],
}
]
arr.sort(function(a, b){
return new Date(b.secondary_fields[3].display_value) - new Date(a.secondary_fields[3].display_value)
})
console.log(arr)
I'm trying to update the 'positionTitle' field of my graphData object with the 'positionTitle fields of my individualData array.
I need to do it accurately, both sets of data have 'accounts' which both have the same id and fullname for user, I was hoping to try and use this to do the matching.
I want the positionTitle's from the users with same account id or name (whichever is easier) to go into the objects fields.
This is currently what I have:
My Object (that i want to update):
graphData = {
"name": "Annual meetings",
"engagementAreas": [{
"id": "1",
"engagementTypes": [{
"name": "forestry",
"engagements": []
},
{
"name": "houses",
"engagements": [{
"name": "engagement1",
"members": [{
"id": "e334", "account": {
"id": "eefe", "fullName": "jim bean"
},
"position": {
"id": "3434",
"positionTitle": "Manager"
}
}]
}]
},
{
"name": "landscaping",
"engagements": [{
"name": "engagement1343",
"members": [{
"id": "e334", "account": {
"id": "123", "fullName": "john boer"
},
"position": {
"id": "4545",
"positionTitle": "Senior Manager"
}
}]
}]
}
]
},
{
"name": "community days",
"engagementTypes": [{
"name": "skyscraping",
"engagements": []
},
{
"name": "tennis",
"engagements": [{
"name": "engagement346",
"members": [{
"id": "34", "account": {
"id": "0010X000048DDMsQAO", "fullName": "edy long"
},
"position": {
"id": "3999434",
"positionTitle": "Ultime Manager"
}
}]
}]
},
{
"name": "Juicing",
"engagements": [{
"name": "347343",
"members": [{
"id": "4546", "account": {
"id": "001b000003WnPy1AAF", "fullName": "jeff bint"
},
"position": {
"id": "35006",
"positionTitle": "Senior Ultimate Manager"
}
}]
}]
}]
}]
}
My array whose positionTitles I want to take:
IndividualData = [{
"account": {
"id": "001b000003WnPy1AAF",
"fullName": "jeff bint"
},
"positions": [{
"id": "a16b0000004AxeBAAS",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Senior Manager, Energy",
"positionLevel": "5-Middle Management & Advisers",
"isPrimary": true,
"startDate": "2016-10-07",
"endDate": null
}]
}, {
"account": {
"id": "0010X000048DDMsQAO",
"fullName": "edy long"
},
"positions": [{
"id": "a160X000004nKfhQAE",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Managing Director",
"positionLevel": "4-Head of Business Unit/Head of Region",
"isPrimary": true,
"startDate": "2018-03-05",
"endDate": null
}]
}, {
"account": {
"id": "123",
"fullName": "john boer"
},
"positions": [{
"id": "325345634634",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Managing Director",
"positionLevel": "4-Head of Business Unit/Head of Region",
"isPrimary": true,
"startDate": "2018-03-05",
"endDate": null
}]
}
]
The function I'm currently using, which does take the first positiontitle field of the array:
const updatedGraphTable = { ...graphData,
engagementAreas: graphData.engagementAreas.map(area => ({ ...area,
engagementTypes: area.engagementTypes.map(type => ({ ...type,
engagements: type.engagements.map(engagement => ({ ...engagement,
members: engagement.members.map(member => ({ ...member,
position: { ...member.position,
positionTitle: IndividualData[0].positions[0].positionTitle
}
}))
}))}))
}))
};
console.log(updatedGraphTable)
console.log('a' + JSON.stringify(updatedGraphTable))
my expected result with the positions updated:
updatedGraphData = {
"name": "Annual meetings",
"engagementAreas": [{
"id": "1",
"engagementTypes": [{
"name": "forestry",
"engagements": []
},
{
"name": "houses",
"engagements": [{
"name": "engagement1",
"members": [{
"id": "e334", "account": {
"id": "eefe", "fullName": "jim bean"
},
"position": {
"id": "3434",
"positionTitle": "Manager"
}
}]
}]
},
{
"name": "landscaping",
"engagements": [{
"name": "engagement1343",
"members": [{
"id": "e334", "account": {
"id": "123", "fullName": "john boer"
},
"position": {
"id": "4545",
"positionTitle": "Managing Director"
}
}]
}]
}
]
},
{
"name": "community days",
"engagementTypes": [{
"name": "skyscraping",
"engagements": []
},
{
"name": "tennis",
"engagements": [{
"name": "engagement346",
"members": [{
"id": "34", "account": {
"id": "0010X000048DDMsQAO", "fullName": "edy long"
},
"position": {
"id": "3999434",
"positionTitle": "Managing Director"
}
}]
}]
},
{
"name": "Juicing",
"engagements": [{
"name": "347343",
"members": [{
"id": "4546", "account": {
"id": "001b000003WnPy1AAF", "fullName": "jeff bint"
},
"position": {
"id": "35006",
"positionTitle": "Senior Manager, Energy"
}
}]
}]
}]
}]
}
My current result:
{
"name": "Annual meetings",
"engagementAreas": [{
"id": "1",
"engagementTypes": [{
"name": "forestry",
"engagements": []
}, {
"name": "houses",
"engagements": [{
"name": "engagement1",
"members": [{
"id": "e334",
"account": {
"id": "eefe"
},
"position": {
"id": "3434",
"positionTitle": "Senior Manager, Energy"
}
}]
}]
}, {
"name": "landscaping",
"engagements": [{
"name": "engagement1343",
"members": [{
"position": {
"id": "4545",
"positionTitle": "Senior Manager, Energy"
}
}]
}]
}]
}, {
"name": "community days",
"engagementTypes": [{
"name": "skyscraping",
"engagements": []
}, {
"name": "tennis",
"engagements": [{
"name": "engagement346",
"members": [{
"id": "34",
"account": {
"id": "3546"
},
"position": {
"id": "3999434",
"positionTitle": "Senior Manager, Energy"
}
}]
}]
}, {
"name": "Juicing",
"engagements": [{
"name": "347343",
"members": [{
"id": "4546",
"account": {
"id": "3545"
},
"position": {
"id": "35006",
"positionTitle": "Senior Manager, Energy"
}
}]
}]
}]
}]
}
Sure, the trick would be to first map your data into an object (so you don't have to search over both arrays all the time), and then conditionally set the value (as I saw that your first manager, doesn't really have a matching position).
So to create the dictionary for usage in your later model, you can first do
// first map the accountId to positions
const accountIdToPositionDict = individualData.reduce( (current, item) => {
current[item.account.id] = (item.positions.filter( position => position.isPrimary )[0] || {} ).positionTitle;
return current;
}, {} );
This would then have an object where accountIdToPositionDict["123"] would be Managing Director, and then change the duplicating logic into:
const updatedGraphTable = { ...graphData,
engagementAreas: graphData.engagementAreas.map(area => ({ ...area,
engagementTypes: area.engagementTypes.map(type => ({ ...type,
engagements: type.engagements.map(engagement => ({ ...engagement,
members: engagement.members.map(member => ({ ...member,
position: { ...member.position,
// use the found positionTitle, or the original one that was given
positionTitle: member.account && accountIdToPositionDict[member.account.id] || member.position.positionTitle
}
}))
}))}))
}))
};
Where the position would then be set based on the found accountId in the dictionary, or the original title if no match was found
const individualData = [{
"account": {
"id": "001b000003WnPy1AAF",
"fullName": "jeff bint"
},
"positions": [{
"id": "a16b0000004AxeBAAS",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Senior Manager, Energy",
"positionLevel": "5-Middle Management & Advisers",
"isPrimary": true,
"startDate": "2016-10-07",
"endDate": null
}]
}, {
"account": {
"id": "0010X000048DDMsQAO",
"fullName": "edy long"
},
"positions": [{
"id": "a160X000004nKfhQAE",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Managing Director",
"positionLevel": "4-Head of Business Unit/Head of Region",
"isPrimary": true,
"startDate": "2018-03-05",
"endDate": null
}]
}, {
"account": {
"id": "123",
"fullName": "john boer"
},
"positions": [{
"id": "325345634634",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Managing Director",
"positionLevel": "4-Head of Business Unit/Head of Region",
"isPrimary": true,
"startDate": "2018-03-05",
"endDate": null
}]
}
];
const graphData = {
"name": "Annual meetings",
"engagementAreas": [{
"id": "1",
"engagementTypes": [{
"name": "forestry",
"engagements": []
},
{
"name": "houses",
"engagements": [{
"name": "engagement1",
"members": [{
"id": "e334", "account": {
"id": "eefe", "fullName": "jim bean"
},
"position": {
"id": "3434",
"positionTitle": "Manager"
}
}]
}]
},
{
"name": "landscaping",
"engagements": [{
"name": "engagement1343",
"members": [{
"id": "e334", "account": {
"id": "123", "fullName": "john boer"
},
"position": {
"id": "4545",
"positionTitle": "Senior Manager"
}
}]
}]
}
]
},
{
"name": "community days",
"engagementTypes": [{
"name": "skyscraping",
"engagements": []
},
{
"name": "tennis",
"engagements": [{
"name": "engagement346",
"members": [{
"id": "34", "account": {
"id": "0010X000048DDMsQAO", "fullName": "edy long"
},
"position": {
"id": "3999434",
"positionTitle": "Ultime Manager"
}
}]
}]
},
{
"name": "Juicing",
"engagements": [{
"name": "347343",
"members": [{
"id": "4546", "account": {
"id": "001b000003WnPy1AAF", "fullName": "jeff bint"
},
"position": {
"id": "35006",
"positionTitle": "Senior Ultimate Manager"
}
}]
}]
}]
}]
};
// first map the accountId to positions
const accountIdToPositionDict = individualData.reduce( (current, item) => {
current[item.account.id] = (item.positions.filter( position => position.isPrimary )[0] || {} ).positionTitle;
return current;
}, {} );
// then use it in the mapping function
const updatedGraphTable = { ...graphData,
engagementAreas: graphData.engagementAreas.map(area => ({ ...area,
engagementTypes: area.engagementTypes.map(type => ({ ...type,
engagements: type.engagements.map(engagement => ({ ...engagement,
members: engagement.members.map(member => ({ ...member,
position: { ...member.position,
// use the found positionTitle, or the original one that was given
positionTitle: member.account && accountIdToPositionDict[member.account.id] || member.position.positionTitle
}
}))
}))}))
}))
};
console.log( updatedGraphTable );
Try the code below.
accountPositions = {};
IndividualData.forEach((data) => {
accountPositions[data.account.id] = data.positions.filter((pos) => {return pos.isPrimary})[0].positionTitle;
});
graphData.engagementAreas.forEach((area) => {
area.engagementTypes.forEach((type) => {
type.engagements.forEach((engagement) => {
engagement.members.forEach((member) => {
if (!accountPositions[member.account.id]) return;
console.log('position updated from ', member.position.positionTitle, 'to', accountPositions[member.account.id]);
member.position.positionTitle = accountPositions[member.account.id];
});
});
});
});
Below is the sample data(Hierarchical data) I want to only that array of object which has IsChecked = true and also all its children with condition isChecked =true.
$scope.treedData = [{
"id": "1",
"text": "Women",
"parentId": null,
"IsChecked": true,
"children": [{
"id": "4",
"text": "Jeans",
"parentId": "1",
"IsChecked": true,
"children": [
{ "id": "5", "text": "Jeans child", "parentId": "4", "IsChecked": true, "children": [] },
{ "id": "6", "text": "Jeans child child", "parentId": "4", "IsChecked": false, "children": [] }
]
}]
},
{
"id": "2",
"text": "Men",
"parentId": null,
"IsChecked": false,
"children": [{ "id": "10", "text": "Sweatshirts", "parentId": "2", "IsChecked": false, "children": [] }]
},
{
"id": "3",
"text": "Kids",
"parentId": null,
"IsChecked": true,
"children": [{ "id": "12", "text": "Toys", "parentId": "3", "IsChecked": false, "children": [] }]
}
];
You can use reduce for that, and use recursion to apply the filter to the children hierarchy as well:
var treeData = [
{ "id": "1", "text": "Women", "parentId": null, "IsChecked": true,
"children": [
{ "id": "4", "text": "Jeans", "parentId": "1", "IsChecked": false, "children":[
{ "id": "5", "text": "Jeans child", "parentId": "4", "IsChecked": true, "children":[] },
{ "id": "6", "text": "Jeans child child", "parentId": "4", "IsChecked": false, "children":[] }
] }]
},
{ "id": "2", "text": "Men", "parentId": null, "IsChecked": false,
"children": [{ "id": "10", "text": "Sweatshirts", "parentId": "2", "IsChecked": false, "children":[]}]
},
{"id": "3", "text": "Kids", "parentId": null, "IsChecked": true,
"children": [{ "id": "12", "text": "Toys", "parentId": "3", "IsChecked": false, "children":[] }]
}
];
checkedTreeData = treeData.reduce(function checkedOnly (acc, obj) {
return obj.IsChecked
? acc.concat(Object.assign({}, obj, { children: obj.children.reduce(checkedOnly, []) }))
: acc;
}, []);
console.log(checkedTreeData);
.as-console-wrapper { max-height: 100% !important; top: 0; }
NB: In JavaScript there is an unwritten rule to not use an initial capital letter for property names, so IsChecked would be with a lower case i: isChecked. Initial capital letters are commonly used for constructors (classes).
Alternative with .filter()
function filterChecked(treeData) {
return treeData.filter(obj => obj.IsChecked)
.map(obj => Object.assign({}, obj, obj.children ?
{ children: filterChecked(obj.children) } : {}))
}
var treeData = [
{ "id": "1", "text": "Women", "parentId": null, "IsChecked": true,
"children": [
{ "id": "4", "text": "Jeans", "parentId": "1", "IsChecked": false, "children":[
{ "id": "5", "text": "Jeans child", "parentId": "4", "IsChecked": true, "children":[] },
{ "id": "6", "text": "Jeans child child", "parentId": "4", "IsChecked": false, "children":[] }
] }]
},
{ "id": "2", "text": "Men", "parentId": null, "IsChecked": false,
"children": [{ "id": "10", "text": "Sweatshirts", "parentId": "2", "IsChecked": false, "children":[]}]
},
{"id": "3", "text": "Kids", "parentId": null, "IsChecked": true,
"children": [{ "id": "12", "text": "Toys", "parentId": "3", "IsChecked": false, "children":[] }]
}
];
console.log(filterChecked(treeData));
.as-console-wrapper { max-height: 100% !important; top: 0; }
use Lodash _.filter and _.every
_.filter(treedData, function(item) {
return _.every([
item.IsChecked,
_.every(item.children, 'IsChecked')
]);
});
if you also want to check condition of children of children you can do it recursively like
_.filter(treedData, function check(item) {
return _.every([
item.IsChecked,
_.size(item.children) === 0 || _.every(item.children, check)
]);
});
My current json (which I created for generating tree structure) is as follows:
[{"text":"glossary","id":"599","parentid":"-1"},
{"text":"title","id":"600","parentid":"599"},
{"text":"","id":"601","parentid":"600"},
{"text":"GlossDiv","id":"602","parentid":"599"},
{"text":"GlossList","id":"603","parentid":"602"},
{"text":"GlossEntry","id":"604","parentid":"603"},
{"text":"GlossTerm","id":"605","parentid":"604"},
{"text":"Standard Generalized Markup Language","id":"606","parentid":"605"},
{"text":"GlossSee","id":"607","parentid":"604"},
{"text":"markup","id":"608","parentid":"607"},
{"text":"SortAs","id":"609","parentid":"604"},
{"text":"SGML","id":"610","parentid":"609"},
{"text":"GlossDef","id":"611","parentid":"604"},
{"text":"para","id":"612","parentid":"611"},
{"text":"","id":"613","parentid":"612"},
{"text":"GlossSeeAlso","id":"614","parentid":"611"},
{"text":"","id":"615","parentid":"614"},
{"text":"XML","id":"616","parentid":"614"},
{"text":"ID","id":"617","parentid":"604"},
{"text":"SGML","id":"618","parentid":"617"},
{"text":"Acronym","id":"619","parentid":"604"},
{"text":"SGML","id":"620","parentid":"619"},
{"text":"Abbrev","id":"621","parentid":"604"},
{"text":"ISO 8879:1986","id":"622","parentid":"621"},
{"text":"title","id":"623","parentid":"602"},
{"text":"","id":"624","parentid":"623"}]`
How to generate a nested json for the above array in Javascript?
You can create a lookup dictionary, to hold the parents, and reference those as you iterate all the entries.
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) {
var parent = dictionary[data[i].parentid];
if (parent) {
if (!parent.children) {
parent.children = [];
}
parent.children.push(data[i]);
}
}
}
JSFiddle: http://jsfiddle.net/TrueBlueAussie/y22ctL8o/1/
Which results in a structure like this:
[{
"text": "glossary",
"id": "599",
"parentid": "-1",
"children": [{
"text": "title",
"id": "600",
"parentid": "599",
"children": [{
"text": "",
"id": "601",
"parentid": "600"
}]
}, {
"text": "GlossDiv",
"id": "602",
"parentid": "599",
"children": [{
"text": "GlossList",
"id": "603",
"parentid": "602",
"children": [{
"text": "GlossEntry",
"id": "604",
"parentid": "603",
"children": [{
"text": "GlossTerm",
"id": "605",
"parentid": "604",
"children": [{
"text": "Standard Generalized Markup Language",
"id": "606",
"parentid": "605"
}]
}, {
"text": "GlossSee",
"id": "607",
"parentid": "604",
"children": [{
"text": "markup",
"id": "608",
"parentid": "607"
}]
}, {
"text": "SortAs",
"id": "609",
"parentid": "604",
"children": [{
"text": "SGML",
"id": "610",
"parentid": "609"
}]
}, {
"text": "GlossDef",
"id": "611",
"parentid": "604",
"children": [{
"text": "para",
"id": "612",
"parentid": "611",
"children": [{
"text": "",
"id": "613",
"parentid": "612"
}]
}, {
"text": "GlossSeeAlso",
"id": "614",
"parentid": "611",
"children": [{
"text": "",
"id": "615",
"parentid": "614"
}, {
"text": "XML",
"id": "616",
"parentid": "614"
}]
}]
}, {
"text": "ID",
"id": "617",
"parentid": "604",
"children": [{
"text": "SGML",
"id": "618",
"parentid": "617"
}]
}, {
"text": "Acronym",
"id": "619",
"parentid": "604",
"children": [{
"text": "SGML",
"id": "620",
"parentid": "619"
}]
}, {
"text": "Abbrev",
"id": "621",
"parentid": "604",
"children": [{
"text": "ISO 8879:1986",
"id": "622",
"parentid": "621"
}]
}]
}]
}, {
"text": "title",
"id": "623",
"parentid": "602",
"children": [{
"text": "",
"id": "624",
"parentid": "623"
}]
}]
}]
}, {
"text": "title",
"id": "600",
"parentid": "599",
"children": [{
"text": "",
"id": "601",
"parentid...rkup",
"id": "608",
"parentid": "607"
}]
}, {
"text": "markup",
"id": "608",
"parentid": "607"
}, {
"text": "SortAs",
"id": "609",
"parentid": "604",
"children": [{
"text": "SGML",
"id": "610",
"parentid": "609"
}]
}, {
"text": "SGML",
"id": "610",
"parentid": "609"
}, {
"text": "GlossDef",
"id": "611",
"parentid": "604",
"children": [{
"text": "para",
"id": "612",
"parentid": "611",
"children": [{
"text": "",
"id": "613",
"parentid": "612"
}]
}, {
"text": "GlossSeeAlso",
"id": "614",
"parentid": "611",
"children": [{
"text": "",
"id": "615",
"parentid": "614"
}, {
"text": "XML",
"id": "616",
"parentid": "614"
}]
}]
}, {
"text": "para",
"id": "612",
"parentid": "611",
"children": [{
"text": "",
"id": "613",
"parentid": "612"
}]
}, {
"text": "",
"id": "613",
"parentid": "612"
}, {
"text": "GlossSeeAlso",
"id": "614",
"parentid": "611",
"children": [{
"text": "",
"id": "615",
"parentid": "614"
}, {
"text": "XML",
"id": "616",
"parentid": "614"
}]
}, {
"text": "",
"id": "615",
"parentid": "614"
}, {
"text": "XML",
"id": "616",
"parentid": "614"
}, {
"text": "ID",
"id": "617",
"parentid": "604",
"children": [{
"text": "SGML",
"id": "618",
"parentid": "617"
}]
}, {
"text": "SGML",
"id": "618",
"parentid": "617"
}, {
"text": "Acronym",
"id": "619",
"parentid": "604",
"children": [{
"text": "SGML",
"id": "620",
"parentid": "619"
}]
}, {
"text": "SGML",
"id": "620",
"parentid": "619"
}, {
"text": "Abbrev",
"id": "621",
"parentid": "604",
"children": [{
"text": "ISO 8879:1986",
"id": "622",
"parentid": "621"
}]
}, {
"text": "ISO 8879:1986",
"id": "622",
"parentid": "621"
}, {
"text": "title",
"id": "623",
"parentid": "602",
"children": [{
"text": "",
"id": "624",
"parentid": "623"
}]
}, {
"text": "",
"id": "624",
"parentid": "623"
}]
But this all depends on what you intend to do with the result. The question is currently ambiguous.
Note: The above double-iteration of data allows for the parents to appear after the children (which may or may not be the case). If the parents always appear first you can combine the logic into one loop.
e.g.
var dictionary = {};
for (var i = 0; i < data.length; i++) {
dictionary[data[i].id] = data[i];
if (data[i].parentid) {
var parent = dictionary[data[i].parentid];
if (parent) {
if (!parent.children) {
parent.children = [];
}
parent.children.push(data[i]);
}
}
}