Traverse to child nodes and find property(upto n levels) - javascript

We have a JSON file:
var response = {
"Status": "Met",
"Text": "Text1",
"Id": "AAA",
"ContentItems": [
{
"Selected": true,
"Text": "Text2",
"Id": "BBB"
},
{
"Status": "Met",
"Text": "Text3",
"Id": "CCC",
"ContentItems": [
{
"Selected": true,
"Text": "Text5",
"Id": "DDD"
},
{
"Status": "Met",
"Text": "Text6",
"Id": "EEE",
"ContentItems": [
{
"Selected": true,
"Text": "Text7",
"Id": "FFF"
},
{
"Selected": true,
"Text": "Text8",
"Id": "GGG"
},
{
"Status": "Met",
"Text": "Text9",
"Id": "III",
"ContentItems": [
{
"Status": "Met",
"Text": "Text11",
"Id": "JJJ",
"ContentItems": [
{
"Text": "Text12",
"Id": "77"
},
{
"Status": "Met",
"Text": "Text13",
"Id": "10",
"ContentItems": [
{
"Text": "Text14",
"Id": "45"
},
{
"Selected": true,
"Text": "Text15",
"Id": "87"
},
{
"Selected": true,
"Text": "Text16",
"Id": "80"
}
]
}
]
},
{
"Status": "Met",
"Text": "Text17",
"Id": "KKK",
"ContentItems": [
{
"Text": "Text18",
"Id": "12"
},
{
"Status": "NotMet",
"Text": "Text19",
"Id": "14",
"ContentItems": [
{
"Text": "Text20",
"Id": "55"
},
{
"Selected": true,
"Text": "Text21",
"Id": "98"
}
]
}
]
}
]
}
]
}
]
}
]
};
From the JSON file we need the following:
1.Return true if all "Status" is "Met".
2.Return false if any "Status" is "NotMet".
Since Child nodes can be any level deep; I used recursion function to traverse to each node and from there i'm looping over the child nodes and recursively calling the function.
I tried this code but its not working as expected.
function isStatusMet(response) {
if (response.Status == 'NotMet') {
return false;
} else {
if (response.ContentItems) {
if(Array.isArray(response.ContentItems)) {
for(var i = 0; i < response.ContentItems.length;i++) {
if (response.ContentItems[i].ContentItems) {
return isStatusMet(response.ContentItems[i]);
} else {
if (response.ContentItems[i].Status == 'NotMet') {
return false;
} else {
continue;
}
}
}
return true;
}
}
}
}

var isStatusMet = function isStatusMet( data ) {
// If the status is NotMet, we finish immediately
if (data.Status === 'NotMet') return false;
// Since only nodes with ContentItems have a status, we check if the node has children and recursively check if every child has no Status of NotMet
else if (data.hasOwnProperty('ContentItems')) return data.ContentItems.every(isStatusMet);
// We're dealing with a child without Status or Childnodes, so we just return true.
// Since the status in not met and the parent node of this node expects in its 'every' loop that we only return false for nodes that have Status NotMet, this makes the recusion work.
else return true;
};
var met = isStatusMet(response);
console.log(met);

The statement return isStatusMet(response.ContentItems[i]); will do a premature exit on any status. It should only return false if the recursive call answers false, or else the loop needs to continue.
Change it to this:
if (response.ContentItems[i].ContentItems) {
if (!isStatusMet(response.ContentItems[i])) return false;
}

You could use Array#every and use it recursive if ContentItems is an array.
var data = { Status: "Met", Text: "Text1", Id: "AAA", ContentItems: [{ Selected: true, Text: "Text2", Id: "BBB" }, { Status: "Met", Text: "Text3", Id: "CCC", ContentItems: [{ Selected: true, Text: "Text5", Id: "DDD" }, { Status: "Met", Text: "Text6", Id: "EEE", ContentItems: [{ Selected: true, Text: "Text7", Id: "FFF" }, { Selected: true, Text: "Text8", Id: "GGG" }, { Status: "Met", Text: "Text9", Id: "III", ContentItems: [{ Status: "Met", Text: "Text11", Id: "JJJ", ContentItems: [{ Text: "Text12", Id: 77 }, { Status: "Met", Text: "Text13", Id: 10, ContentItems: [{ Text: "Text14", Id: 45 }, { Selected: true, Text: "Text15", Id: 87 }, { Selected: true, Text: "Text16", Id: 80 }] }] }, { Status: "Met", Text: "Text17", Id: "KKK", ContentItems: [{ Text: "Text18", Id: 12 }, { Status: "NotMet", Text: "Text19", Id: 14, ContentItems: [{ Text: "Text20", Id: 55 }, { Selected: true, Text: "Text21", Id: 98 }] }] }] }] }] }] },
result = [data].every(function iter(a) {
return a.Status !== 'NotMet' && (!Array.isArray(a.ContentItems) || a.ContentItems.every(iter));
});
console.log(result);

Related

Loop through JSON in dataLayer

I would like to get the summed value of all the arrays in the "products" object (price * quantity). The summed value should be returned in the return.
Do you have any ideas how to do that?
{
"event": "checkout",
"ecommerce": {
"checkout": {
"actionField": {
"step": 2,
"option": "Initiate checkout",
"action": "checkout"
},
"products": [
{
"id": "52",
"name": "Turystyczna kuchenka gazowa SMILE-KN-03/1K",
"price": 161.788618,
"brand": "",
"category": "kuchenki-elektryczne-i-gazowe",
"variant": "",
"quantity": "1"
},
{
"id": "36",
"name": "Kuchnia gazowa MPM-51-KGF-21",
"price": 641.463415,
"brand": "",
"category": "kuchnie-gazowe",
"variant": "",
"quantity": "1"
}
]
}
},
"gtm.uniqueEventId": 12
}
const g = {
event: 'checkout',
ecommerce: {
checkout: {
actionField: {
step: 2,
option: 'Initiate checkout',
action: 'checkout',
},
products: [
{
id: '52',
name: 'Turystyczna kuchenka gazowa SMILE-KN-03/1K',
price: 161.788618,
brand: '',
category: 'kuchenki-elektryczne-i-gazowe',
variant: '',
quantity: '1',
},
{
id: '36',
name: 'Kuchnia gazowa MPM-51-KGF-21',
price: 641.463415,
brand: '',
category: 'kuchnie-gazowe',
variant: '',
quantity: '1',
},
],
},
},
'gtm.uniqueEventId': 12,
};
const c = g.ecommerce.checkout.products.reduce((acc, curr) => {
acc += curr.price * curr.quantity;
return acc;
}, 0);
console.log(c)
guess you want something like this?

How To Get The Parent value from Json for this select2

var preload_data = [{
"id": 2049,
"text": "style",
"children": [{
"id": "6906957ed912c883",
"text": "Country"
}, {
"id": "d239d844608fdbcf",
"text": "Christmas"
}]
}, {
"id": 0,
"text": "unassigned",
"children": [{
"id": "52d8e1e8d419bb61",
"text": "Punk"
}, {
"id": "88b9826121aeb89b",
"text": "Upbeat"
}, {
"id": "8485e6dd8e33fc50",
"text": "test arda"
}, {
"id": "da9fa55495a4a463",
"text": "test1"
}, {
"id": "feb1177719f4b5a4",
"text": "test arda 3"
}, {
"id": "64a2ae4ec2c0a1ef",
"text": "Feel Good"
}, {
"id": "2512f7946f660dc5",
"text": "Happy"
}, {
"id": "b1e7203207bd068f",
"text": "Love"
}, {
"id": "fb3a42b8abbf975a",
"text": "Reminiscent"
}, {
"id": "56d60aed1278c5a0",
"text": "Indie"
}, {
"id": "5733de46970ac503",
"text": "Rock"
}, {
"id": "801c33b478d1d5be",
"text": "Singer Songwriter"
}, {
"id": "ee4c6f5c12782bb9",
"text": "World"
}, {
"id": "4605140218eb9e52",
"text": "Reality"
}, {
"id": "92934140c305706e",
"text": "Pop"
}, {
"id": "f40f55db44dc0846",
"text": "Acoustic"
}, {
"id": "07b3c4640e84bfeb",
"text": "Folk"
}]
}]
and I want the output for dropdown list
Style:Christmas for example
this is the select2 code
$("#hidStyles").select2({
containerCssClass: 'styleContainer',
data: preload_data,
width: '100%',
allowClear: true,
multiple: true,
dropdownCssClass: 'select2-hidden',
placeholder: 'Please enter the name of style here to assign it to this album',
formatSelection: format1,
escapeMarkup : function(m) { return m;},
formatSearching: null
//formatSelection : format
});
and this is How I format the Json :
function format1(item) {
opt = $("#hidStyles").find(':selected');
sel = opt.text;
//og = opt.closest(".select2-results-dept-0").attr(".select2-result-label");
ogx = opt.text.data.text;
return ogx + ':' + item.text;
}
how can I get the value so that it's like style : christmas
https://jsfiddle.net/jna7ft1c/3/
I am sorry the jsfiddle I am not familiar with for making the front end, but mostly the code is like written there

Toggle property of nested array of object - JS

I have an array of objects with 3 levels. I want to target the innermost child with property 'code'. If code is present, then update the child as well as the parent object with selected: true. If the property already is true, then sending in the same value should set the child to selected: false (toggle)
This is what I have going so far. If selected is true for a child, sending in another code should set selected: true for the corresponding child and selected: false for the child which had true for selected property.
Also, if selected is true for a child, defaultCollapsed property should be false for the child as well as parent and grandparent. Ifs elected is false for a child, defaultCollapsed property should be true for the child as well as parent and grandparent
const data = [{
"label": "Grand Parent 1",
"index": 0,
"code": "GRAND_PARENT_1",
"defaultCollapsed": true,
"items": [{
"id": 1,
"items": [{
"id": 100,
"label": "Child 1",
"url": "#CHILD_1",
"code": "CHILD_1",
},
{
"id": 200,
"label": "Child 2",
"url": "#CHILD_2",
"code": "CHILD_2"
},
{
"id": 300,
"label": "Child 3",
"url": "#CHILD_3",
"code": "CHILD_3"
},
{
"id": 400,
"label": "Child 4",
"url": "#CHILD_4",
"code": "CHILD_4"
}
],
"defaultCollapsed": true,
"label": "Parent 1",
"selected": true,
},
{
"id": 2,
"items": [],
"defaultCollapsed": true,
"label": "Parent 2"
},
{
"id": 3,
"items": [],
"defaultCollapsed": true,
"label": "Parent 3"
},
{
"id": 4,
"items": [],
"defaultCollapsed": true,
"label": "Parent 4"
}
]
},
{
"label": "Grand Parent 2",
"index": 1,
"code": "GRAND_PARENT_2",
"defaultCollapsed": true,
"items": []
},
{
"label": "Grand Parent 3",
"index": 2,
"code": "GRAND_PARENT_3",
"defaultCollapsed": true,
"items": []
}
]
function select(items, key, value) {
if (!Array.isArray(items)) {
return false;
}
for (const item of items) {
if (item.code === value || select(item.items, key, value)) {
item.selected = !item.selected;
item.defaultCollapsed = false;
return true;
}
}
return false;
}
function reset(items) {
if (!Array.isArray(items)) {
return;
}
for (const item of items) {
if (item.selected) {
reset(item.items);
item.selected = false;
break;
}
}
}
function resetAndSelect(data, key, value) {
reset(data);
select(data, key, value);
}
resetAndSelect(data, 'code', 'CHILD_1')
console.log('CHILD_1',data)
resetAndSelect(data, 'code', 'CHILD_2')
console.log('CHILD_2',data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
If code is CHILD_1:
[{
"label": "Grand Parent 1",
"index": 0,
"code": "GRAND_PARENT_1",
"defaultCollapsed": true,
"selected": true,
"items": [{
"id": 1,
"items": [{
"id": 100,
"label": "Child 1",
"url": "#CHILD_1",
"code": "CHILD_1",
"selected": true,
},
{
"id": 200,
"label": "Child 2",
"url": "#CHILD_2",
"code": "CHILD_2"
},
{
"id": 300,
"label": "Child 3",
"url": "#CHILD_3",
"code": "CHILD_3"
},
{
"id": 400,
"label": "Child 4",
"url": "#CHILD_4",
"code": "CHILD_4"
}
],
"defaultCollapsed": false,
"label": "Parent 1",
"selected": true,
},
{
"id": 2,
"items": [],
"defaultCollapsed": true,
"label": "Parent 2"
},
{
"id": 3,
"items": [],
"defaultCollapsed": true,
"label": "Parent 3"
},
{
"id": 4,
"items": [],
"defaultCollapsed": true,
"label": "Parent 4"
}
]
},
{
"label": "Grand Parent 2",
"index": 1,
"code": "GRAND_PARENT_2",
"defaultCollapsed": true,
"items": []
},
{
"label": "Grand Parent 3",
"index": 2,
"code": "GRAND_PARENT_3",
"defaultCollapsed": true,
"items": []
}
]
If the above output is the actual data, and the code is CHILD_1 again, I need to toggle the selected property of the child as well the corresponding parents.
[{
"label": "Grand Parent 1",
"index": 0,
"code": "GRAND_PARENT_1",
"defaultCollapsed": true,
"selected": false,
"items": [{
"id": 1,
"items": [{
"id": 100,
"label": "Child 1",
"url": "#CHILD_1",
"code": "CHILD_1",
"selected": false,
},
{
"id": 200,
"label": "Child 2",
"url": "#CHILD_2",
"code": "CHILD_2"
},
{
"id": 300,
"label": "Child 3",
"url": "#CHILD_3",
"code": "CHILD_3"
},
{
"id": 400,
"label": "Child 4",
"url": "#CHILD_4",
"code": "CHILD_4"
}
],
"defaultCollapsed": false,
"label": "Parent 1",
"selected": false,
},
{
"id": 2,
"items": [],
"defaultCollapsed": true,
"label": "Parent 2"
},
{
"id": 3,
"items": [],
"defaultCollapsed": true,
"label": "Parent 3"
},
{
"id": 4,
"items": [],
"defaultCollapsed": true,
"label": "Parent 4"
}
]
},
{
"label": "Grand Parent 2",
"index": 1,
"code": "GRAND_PARENT_2",
"defaultCollapsed": true,
"items": []
},
{
"label": "Grand Parent 3",
"index": 2,
"code": "GRAND_PARENT_3",
"defaultCollapsed": true,
"items": []
}
]
You can do this by creating recursive function using forEach loop and passing array of parents down with recursion so that you can update its selected property.
const data = [{"label":"Grand Parent 1","index":0,"code":"GRAND_PARENT_1","defaultCollapsed":true,"items":[{"id":1,"items":[{"id":100,"label":"Child 1","url":"#CHILD_1","code":"CHILD_1"},{"id":200,"label":"Child 2","url":"#CHILD_2","code":"CHILD_2"},{"id":300,"label":"Child 3","url":"#CHILD_3","code":"CHILD_3"},{"id":400,"label":"Child 4","url":"#CHILD_4","code":"CHILD_4"}],"defaultCollapsed":true,"label":"Parent 1","selected":true},{"id":2,"items":[],"defaultCollapsed":true,"label":"Parent 2"},{"id":3,"items":[],"defaultCollapsed":true,"label":"Parent 3"},{"id":4,"items":[],"defaultCollapsed":true,"label":"Parent 4"}]},{"label":"Grand Parent 2","index":1,"code":"GRAND_PARENT_2","defaultCollapsed":true,"items":[]},{"label":"Grand Parent 3","index":2,"code":"GRAND_PARENT_3","defaultCollapsed":true,"items":[]}]
function update(data, key, value, parents = []) {
data.forEach(e => {
if (e[key] === value) {
if (parents.length) {
e.selected = !e.selected;
parents.forEach(p => {
p.defaultCollapsed = !e.selected
p.selected = e.selected
})
data.forEach(s => {
if (s != e && s.selected) s.selected = false;
});
}
}
if (e.items && e.items.length) {
update(e.items, key, value, [...parents, e])
}
})
}
update(data, 'code', 'CHILD_4')
update(data, 'code', 'CHILD_4')
update(data, 'code', 'CHILD_2')
update(data, 'code', 'CHILD_1')
console.log(data)
You could toggle the target node and leave the rest as true, for the path to the item.
function update(array, value) {
var found = false;
array.forEach(o => {
var sub = update(o.items || [], value),
check = o.code === value;
if (check) {
o.selected = !o.selected
found = o.selected;
} else {
o.selected = sub;
if (sub) found = o.selected;
}
o.defaultCollapsed = !o.selected;
});
return found;
}
var data = [{ label: "Grand Parent 1", index: 0, code: "GRAND_PARENT_1", defaultCollapsed: true, items: [{ id: 1, items: [{ id: 100, label: "Child 1", url: "#CHILD_1", code: "CHILD_1" }, { id: 200, label: "Child 2", url: "#CHILD_2", code: "CHILD_2" }, { id: 300, label: "Child 3", url: "#CHILD_3", code: "CHILD_3" }, { id: 400, label: "Child 4", url: "#CHILD_4", code: "CHILD_4" }], defaultCollapsed: false, label: "Parent 1" }, { id: 2, items: [], defaultCollapsed: true, label: "Parent 2" }, { id: 3, items: [], defaultCollapsed: true, label: "Parent 3" }, { id: 4, items: [], defaultCollapsed: true, label: "Parent 4" }] }, { label: "Grand Parent 2", index: 1, code: "GRAND_PARENT_2", defaultCollapsed: true, items: [] }, { label: "Grand Parent 3", index: 2, code: "GRAND_PARENT_3", defaultCollapsed: true, items: [] }];
update(data, 'CHILD_1');
console.log(data);
update(data, 'CHILD_1');
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Creating a new array from the parents of array child element

I have the following array
{
"id": "111",
"name": "1111",
"children": [
{
"id": "22222",
"name": "2222",
"children": [
{
"id": "AAAA",
"name": "AAAA",
"children": [
{
"id": "DDD",
"name": "DDD"
},
{
"id": "EEE",
"name": "EEE"
}
]
},
{
"id": "BBBB",
"name": "BBB",
"children": [
{
"id": "FFF",
"name": "FFF"
},
{
"id": "GGG",
"name": "GGG",
"children": [
{
"id": "7777",
"name": "7777"
},
{
"id": "8888",
"name": "8888"
}
]
}
]
}
]
}
]
}
And I would like to create an array with the parents of a child by its ID.
So for example if I wanted to get the path to the child with ID "FFF", then the array would look like something like this:
["1111", "2222", "BBB", "FFF"]
How could I go about doing that?
You could take an iterative and recursive approach.
function getItems({ children, ...object }, key, value) {
var temp;
if (object[key] === value) return [object];
if (children) children.some(o => temp = getItems(o, key, value));
return temp && [object, ...temp];
}
var data = { id: "111", name: "1111", children: [{ id: "22222", name: "2222", children: [{ id: "AAAA", name: "AAAA", children: [{ id: "DDD", name: "DDD" }, { id: "EEE", name: "EEE" }] }, { id: "BBBB", name: "BBB", children: [{ id: "FFF", name: "FFF" }, { id: "GGG", name: "GGG", children: [{ id: "7777", name: "7777" }, { id: "8888", name: "8888" }] }] }] }] };
console.log(getItems(data, 'id', 'FFF'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
You could implement a recursive search to find all paths and return the correct one when you reach the desired name-value pair.
const isObject = (obj) => obj === Object(obj);
let data = loadData();
let expected = [ '1111', '2222', 'BBB', 'FFF' ];
let actual = findPath(data, 'name', 'FFF');
console.log(JSON.stringify(expected) === JSON.stringify(actual));
function findPath(data, key, value, includeIndicies=false) {
let opts = { found : null, includeIndicies : includeIndicies };
findPathInternal(data, key, value, opts, []);
return opts.found;
}
function findPathInternal(node, key, val, opts, path) {
if (Array.isArray(node)) {
for (let i = 0; i < node.length; i++) {
findPathInternal(node[i], key, val, opts, opts.includeIndicies ? path.concat(i) : path);
}
} else if (isObject(node)) {
if (node[key] === val) {
opts.found = path.concat(val); return; // Exit
} else {
let keys = Object.keys(node);
for (let i = 0; i < keys.length; i++) {
findPathInternal(node[keys[i]], key, val, opts, path.concat(node[key]));
}
}
}
};
function loadData() {
return {
"id": "111",
"name": "1111",
"children": [{
"id": "22222",
"name": "2222",
"children": [{
"id": "AAAA",
"name": "AAAA",
"children": [{
"id": "DDD",
"name": "DDD"
},
{
"id": "EEE",
"name": "EEE"
}
]
},
{
"id": "BBBB",
"name": "BBB",
"children": [{
"id": "FFF",
"name": "FFF"
},
{
"id": "GGG",
"name": "GGG",
"children": [{
"id": "7777",
"name": "7777"
},
{
"id": "8888",
"name": "8888"
}
]
}
]
}
]
}]
};
}
.as-console-wrapper { top: 0; max-height: 100% !important; }

Child items in kendo grid

How can i bind my child data in one column?
I want to write "Technology,Economy,Life" in same column and same row. But i think i need to loop in "Category". How can i do this, any idea?
My Data:
{
"ParentId": "00000000-0000-0000-0000-000000000000",
"Title": null,
"UserGroupModel": null,
"EntityAccessData": [
{
"EntityTitle": "User",
"Access": {
"Id": "59d0c6f7-8f93-497a-854d-bdd4a42ade94",
"Title": "Can Delete"
},
"Category": [
{
"Id": "00000000-0000-0000-0000-000000000000",
"Title": "Technology"
},
{
"Id": "00000000-0000-0000-0000-000000000000",
"Title": "Economy"
},
{
"Id": "00000000-0000-0000-0000-000000000000",
"Title": "Life"
}
],
"HasAccess": true
},
{
"EntityTitle": "UserGroup",
"Access": {
"Id": "7c65be44-11b0-4cf4-9104-0ad999e7e280",
"Title": "Can Edit"
},
"Category": [
{
"Id": "00000000-0000-0000-0000-000000000000",
"Title": "Technology"
},
{
"Id": "00000000-0000-0000-0000-000000000000",
"Title": "Economy"
},
{
"Id": "00000000-0000-0000-0000-000000000000",
"Title": "Life"
}
],
"HasAccess": true
}
]
}
My Script:
$("#grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: "/getData" },
schema: {
data: "EntityAccessData"
},
group: [{
field: "EntityTitle"
}],
},
columns: [
{
field: "Access.Id",
title: "ID"
},
{
field: "Access.Title",
title: "Access title"
},
{
field: "HasAccess",
title: "has access"
},
{
field: "Category.Title", // ***wrong***
title: "Category"
},
]
});
Define the schema as follow:
schema: {
data : "EntityAccessData",
model: {
CategoryTitle: function () {
var category = [];
$.each(this.Category, function(idx, elem) {
category.push(elem.Title);
});
return category.join(",");
}
}
},
Where I add an additional field CategoryTitle that is the result of joining the Title of the Category array and then define the column as:
{
field: "CategoryTitle()",
title: "Category"
}

Categories

Resources