i'm using google apps script, and I have a JSON array consisting of nested parent and child objects.
"logisticalHierarchies": [
{
"product_key_id": 48232671,
"gtin": "05449000696878",
"lastRequest": null,
"productIdentifier": null,
"children": [
{
"product_key_id": 48232673,
"gtin": "05449000283863",
"quantity": 130,
"productIdentifier": null,
"children": [
{
"product_key_id": 48232457,
"gtin": "05449000283856",
"quantity": 4,
"productIdentifier": null,
"children": [
{
"product_key_id": 48232675,
"gtin": "05449000214843",
"quantity": 6,
"productIdentifier": null,
"children": [],
"contentOwner_id": 10525,
"isMainHierarchyUnit": false,
I would like by entering the GTIN object as parameters, to succeed in recovering the GTIN object of the father of the product that I have just entered.
For example if I enter the GTIN: 05449000283856
I get the GTIN FATHER: 05449000283863
For the moment I am able to retrieve only the first GTIN of the list (the first father) using this script:
var url='https://apis.alkemics.com/public/v1/products?'+params;
//Logger.log(url);
var content =UrlFetchApp.fetch(url, options);
//Logger.log(content);
//Logger.log(content.getResponseCode())
if (content. getResponseCode() ==200) {
var return =JSON.parse(content.getContentText());
next_page=back.next_page;
var data=return.data;
for(i=0; i<data.length;i++) {
var product=data[i]; // A product in JSON format
var childrens = data.map(({logisticalHierarchies}) => logisticalHierarchies.map(o => [o.children?.gtin || ""]));
Logger.log(childrens)
var line=[
product.gtin,
product.logisticalHierarchies[0] != null? product.logisticalHierarchies[0].children[0].gtin: ' ',
];
So a recursion would help, passing the father as you go into deeper level. This one written for readability not for efficiency as you should break from the loop early if you find the searched item.
var logisticalHierarchies = [{
"product_key_id": 48232671,
"gtin": "05449000696878",
"lastRequest": null,
"productIdentifier": null,
"children": [{
"product_key_id": 48232673,
"gtin": "05449000283863",
"quantity": 130,
"productIdentifier": null,
"children": [{
"product_key_id": 48232457,
"gtin": "05449000283856",
"quantity": 4,
"productIdentifier": null,
"children": [{
"product_key_id": 48232675,
"gtin": "05449000214843",
"quantity": 6,
"productIdentifier": null,
"children": [],
"contentOwner_id": 10525,
"isMainHierarchyUnit": false,
}, {
"product_key_id": 12323,
"gtin": "05449000214847",
"quantity": 6,
"productIdentifier": null,
"children": [],
"contentOwner_id": 10525,
"isMainHierarchyUnit": false,
}]
}]
}]
}]
function find_gtin_father(arr, gtin, parent) {
parent = parent || null;
var found = null;
arr.forEach(function(item) {
if (item.gtin === gtin) {
found = parent;
} else {
if (item.children) {
found = found || find_gtin_father(item.children, gtin, item);
}
}
})
return found;
}
var item = find_gtin_father(logisticalHierarchies, "05449000214847")
console.log(item)
.as-console-wrapper {max-height: 100% !important}
Related
This question already has answers here:
How to find a node in a tree with JavaScript
(19 answers)
Javascript - Find path to object reference in nested object
(3 answers)
Closed 1 year ago.
I am working on an angular application. My data is as follows
data= [
{
"id": 2,
"name": "Jamie",
"objectId": 200,
"parentId": null,
"children": [
{
"id": 98,
"name": "Rose",
"objectId": 100,
"parentId": 200,
"children": [
{
"id": 1212,
"name": "julie",
"objectId": 500,
"parentId": 100,
"children": []
}
]
},
{
"id": 67,
"name": "Kosy",
"objectId": 700,
"parentId": 200,
"children": []
}
]
}
]
I will be having input id and name. Suppose in my method I get id as 1212 and name as "julie". So I want to go to that node whose id is 1212 and name is equal to
"julie", once this condition is met. I need to check parentId in children is equal to objectId in parent till parentId becomes null.
If parent id becomes null then it is considered as last node and then I want to have my data in the array in following format. For id 1212 and name
"julie" resultArray is
resultArray = ["Jamie/Rose/Julie "]. Data starting from parent to children separated by slash.
Another example is if I get id as 67 and name "Kosy". then result array will be
resultArray = ["Jamie/Kosy"]
As parentId of Kosy is 200 and ObjectId of Jamie is 200, which indicate that Jamie is parent of Kosy, that's why data should look like this. want to have dynamic code as at run time data can be huge but structure and logic will be same as mentioned above
How can I do this
I wrote the code for this problem. Please try the following code. This is one of the typical tree-search problem. One point what sets it apart from traditional tree search is checking its parent. That was easily solved here.
const data = [
{
"id": 2,
"name": "Jamie",
"objectId": 200,
"parentId": null,
"children": [
{
"id": 98,
"name": "Rose",
"objectId": 100,
"parentId": 200,
"children": [
{
"id": 1212,
"name": "julie",
"objectId": 500,
"parentId": 100,
"children": []
}
]
},
{
"id": 67,
"name": "Kosy",
"objectId": 700,
"parentId": 200,
"children": []
}
]
}
];
// function that search the target in a node(not a array)
// In order for this function to return true, id comparison from the final node to this node should be passed as well
const findInNode = (node, id, name, output) => {
if (node.name === name && node.id === id) { // self test
return true;
} else {
const children = node.children;
if (!children) return false;
// find in children
for (let child of children) {
// output.paths is the current search path
output.paths.push(child.name);
if (findInNode(child, id, name, output)) {
// if found, compare the self objectId and child's parentId
return child.parentId === node.objectId;
}
output.paths.pop();
}
}
}
// function that search the target in an array, for use at the top-most level
const findInArray = (nodes, id, name, output) => {
for (let node of nodes) {
output.paths.push(node.name);
if (findInNode(node, id, name, output)) {
if (!node.parentId) {
output.found = true;
break;
}
}
output.paths.pop();
}
}
output = { paths: [], found: false };
findInArray(data, 1212, 'julie', output);
console.log(output.found);
console.log(output.paths.join('/'));
This is my JSON Object in this i want to remove "item" key from json and want to keep its inner object include with "children" and its tree like JOSN. How can I do this?
[
{
"item": {
"id": 11865,
"parentid": null,
"levelid": 63,
"name": "Total"
},
"children": [
{
"item": {
"id": 10143,
"parentid": 11865,
"levelid": 19,
"name": "Productive"
}
}
]
}
]
If I'm understanding what you want your object to look like after correctly, then this should do the trick:
var arrayOfObjects = [
{
"item": {
"id": 11865,
"parentid": null,
"levelid": 63,
"name": "Total"
},
"children": [
{
"item": {
"id": 10143,
"parentid": 11865,
"levelid": 19,
"name": "Productive"
}
}
]
}
]
arrayOfObjects.forEach(function(obj) {
obj.id = obj.item.id;
obj.parentid = obj.item.parentid;
obj.levelid = obj.item.levelid;
obj.name = obj.item.name;
delete obj.item;
});
All this is doing is manually moving the data from obj.item to obj and then deleting obj.item entirely.
I would do this:
//your original array of objects
var array = [{
"item": {
"id": 11865,
"parentid": null,
"levelid": 63,
"name": "Total"
},
"children": [
{
"item": {
"id": 10143,
"parentid": 11865,
"levelid": 19,
"name": "Productive"
}
}
]
}, ...];
array.forEach(function(parent) {
flattenKey(parent, 'item');
});
function flattenKey(parent, keyName) {
var section = parent[keyName];
var child = section ? section : {};
var keys = Object.keys(child);
keys.forEach(function(key) {
parent[key] = child[key];
})
delete parent[keyName];
}
basically, the function flattenKey would flatten any key for a given object (given its key).
logic is similar to other solutions here: iterate through child keys and assign their values to the parent object (flattening).
then it deletes the child key after step 1.
try
objArray = objArray.map( function(value){
var item = value.item;
for( var key in item )
{
value[key] = item[key];
}
delete value.item;
return value;
});
DEMO
Explanation
1) Use map to iterate on each item (value) of this given array objArray.
2) Get the item property of value, assign them to value directly
3) Finally delete the item property of the value.
Faster option
objArray = objArray.map( function(value){
var item = value.item;
var itemKeys = Object.keys(item);
for( var counter = 0; counter < itemKeys.length; counter++ )
{
value[itemKeys[counter]] = item[itemKeys[counter]];
}
delete value.item;
return value;
});
You can use a recursion, which keeps the content of item and adds the children property as well.
function delItem(a, i, aa) {
var children = a.children;
if (a.item) {
aa[i] = a.item;
aa[i].children = children;
delete a.item;
}
Array.isArray(children) && children.forEach(delItem);
}
var array = [{ "item": { "id": 11865, "parentid": null, "levelid": 63, "name": "Total" }, "children": [{ "item": { "id": 10143, "parentid": 11865, "levelid": 19, "name": "Productive" } }] }];
array.forEach(delItem);
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');
I have been playing around with the Angular UI Tree drag and drop and have come by an issue that has stumped me. The json is being received from my services. When it is received by my controller, I must format it properly with an empty array so it will be able to hold childen:
Formatting:
function categorySuccessPost(data) {
var emptyCategoryArray = {
Categories: []
}
for (var i = 0; i < data.length; i++) {
$.extend(data[i], emptyCategoryArray);
}
$scope.categoryData = data;
}
It is now formatted and looks like:
[ { "CategoryId": 27054, "MerchantId": 5594, "ProductCategoryId": 1310,
"Name": "BulkUpload", "Description": "BulkUpload", "DateCreated":
"/Date(1446793200000-0000)/", "IsActive": true, "IsDefault": false, "ItemCount":
5, "ResponseStatus": { "ErrorCode": "SUCCESS" }, "TotalRecordCount": 15,
"Categories": [] }, { "CategoryId": 23267, "MerchantId": 5594,
"ProductCategoryId": 818, "Name": "Coupon", "Description": "Coupon",
"DateCreated": "/Date(-62135596800000-0000)/", "IsActive": true, "IsDefault":
true, "ItemCount": 1, "ResponseStatus": { "ErrorCode": "SUCCESS" },
"TotalRecordCount": 15, "Categories": [] } }
I have tried two different functions when attempting to add a child:
Function 1 (Uses model value):
$scope.newSubItem = function (scope) {
var currentCategoryData = scope.$modelValue;
currentCategoryData.Categories.push({
CategoryId: currentCategoryData.CategoryId * 10 + currentCategoryData.Categories.length,
Name: currentCategoryData.Name + '.' + (currentCategoryData.Categories.length + 1),
Categories: []
});
};
Function 2 (Uses index of object in the array, and yes, I have made sure the correct index is being passed):
$scope.newSubItem = function (index) {
var array = $scope.categoryData;
array[index].Categories.push({
CategoryId: 12312,
Name: 'test',
Categories: []
});
};
The issue is that instead of pushing the new data to the selected index, it adds the json to every Categories :
[ { "CategoryId": 27054, "MerchantId": 5594, "ProductCategoryId": 1310,
"Name": "BulkUpload", "Description": "BulkUpload", "DateCreated":
"/Date(1446793200000-0000)/", "IsActive": true, "IsDefault": false, "ItemCount":
5, "ResponseStatus": { "ErrorCode": "SUCCESS" }, "TotalRecordCount": 15,
"Categories": [ { "CategoryId": 12312, "Name": "test", "Categories": [] } ] }, {
"CategoryId": 23267, "MerchantId": 5594, "ProductCategoryId": 818, "Name": "Coupon", "Description": "Coupon", "DateCreated": "/Date(-62135596800000-
0000)/", "IsActive": true, "IsDefault": true, "ItemCount": 1, "ResponseStatus":
{ "ErrorCode": "SUCCESS" }, "TotalRecordCount": 15, "Categories": [ {
"CategoryId": 12312, "Name": "test", "Categories": [] } ] }
I am not showing the HTML because it does not appear to be an issue. Here's where I have narrowed it down to, but still have no explanation:
If I use the data that goes through the $.extend method then it adds a child to every parent. But if I copy the json that is generated after the formatting, put it into and object and then read from that, then it only adds a child to the selected parent like I want. But it is necessary to add the empty array. Any idea why this is happening and any solution?
EDIT
One more piece of information that may be important: When I add a full Category (different function), rather than adding a subcategory and then try to add a child to the newly generated category then it works correctly (adding only a child to that category):
$scope.addCategory = function () {
var name = $scope.categoryName;
// Temporary
var categoryId = Math.floor((Math.random() * 50000) + 1)
console.log(name, categoryId)
$scope.categoryData.unshift({ CategoryId: categoryId, Name: name, Categories: [] })
$scope.categoryName = "";
$("#addCategoryModal").modal('hide');
Notification.success({ message: 'Category Added Successfully!', delay: 3000 });
}
I'm still not sure exactly why this is happening, but this was my solution to fixing the issue:
Remove the $.extend for loop and $.extend function:
function categorySuccessPost(data) {
$scope.categoryData = data;
}
When adding an item, check if the array has been initialized, if not, create it in the current scope:
$scope.newSubItem = function (scope) {
var currentCategoryData = scope.$modelValue;
if(currentCategoryData.Categories === 'undefined'){
currentCategoryData.Categories = [];
}
currentCategoryData.Categories.push({
CategoryId: currentCategoryData.CategoryId * 10 + currentCategoryData.Categories.length,
Name: currentCategoryData.Name + '.' + (currentCategoryData.Categories.length + 1),
Categories: []
});
};
The issue with this method is that you can no longer drag a node into an empty parent.
I am trying to create a category tree using the array of json objects below.
I want to set a category as a child of another category if its parent equals the id of the other, and I want the posts also to be a children of that category instead of having a separate field for posts, I'll add a flag field that if it is a category or not isParent.
It looks like its working alright, but as you may see, if a category has both category and post as child, it'll only show the categories. Another problem with that is if the post has a null value on its array, it will still push them as children.
What are the mistakes in my code, or is there a simpler or better solution to this?
var tree = unflatten(getData());
var pre = document.createElement('pre');
console.log(tree);
pre.innerText = JSON.stringify(tree, null, 4);
document.body.appendChild(pre);
function unflatten(array, parent, tree) {
tree = typeof tree !== 'undefined' ? tree : [];
parent = typeof parent !== 'undefined' ? parent : {
id: 0
};
_.map(array, function(arr) {
_.set(arr, 'isParent', true);
});
var children = _.filter(array, function(child) {
return child.parent == parent.id;
});
if (!_.isEmpty(children)) {
if (parent.id == 0) {
tree = children;
} else {
parent['children'] = children;
}
_.each(children, function(child) {
var posts = _.map(child.posts, function(post) {
return _.set(post, 'isParent', false);
});
child['children'] = posts;
delete child.posts;
unflatten(array, child);
});
}
return tree;
}
function getData() {
return [{
"id": "c1",
"parent": "",
"name": "foo",
"posts": [{
"id": "p1"
}]
}, {
"id": "c2",
"parent": "1",
"name": "bar",
"posts": [{
"id": "p2"
}]
}, {
"id": "c3",
"parent": "",
"name": "bazz",
"posts": [
null
]
}, {
"id": "c4",
"parent": "3",
"name": "sna",
"posts": [{
"id": "p3"
}]
}, {
"id": "c5",
"parent": "3",
"name": "ney",
"posts": [{
"id": "p4"
}]
}, {
"id": "c6",
"parent": "5",
"name": "tol",
"posts": [{
"id": "p5"
}, {
"id": "p6"
}]
}, {
"id": "c7",
"parent": "5",
"name": "zap",
"posts": [{
"id": "p7"
}, {
"id": "p8"
}, {
"id": "p9"
}]
}, {
"id": "c8",
"parent": "",
"name": "quz",
"posts": [
null
]
}, {
"id": "c9",
"parent": "8",
"name": "meh",
"posts": [{
"id": "p10"
}, {
"id": "p11"
}]
}, {
"id": "c10",
"parent": "8",
"name": "ror",
"posts": [{
"id": "p12"
}, {
"id": "p13"
}]
}, {
"id": "c11",
"parent": "",
"name": "gig",
"posts": [{
"id": "p14"
}]
}, {
"id": "c12",
"name": "xylo",
"parent": "",
"posts": [{
"id": "p15"
}]
}, {
"id": "c13",
"parent": "",
"name": "grr",
"posts": [{
"id": "p16"
}, {
"id": "p17"
}, {
"id": "p14"
}, {
"id": "p18"
}, {
"id": "p19"
}, {
"id": "p20"
}]
}]
}
<script src="//cdn.jsdelivr.net/lodash/3.10.1/lodash.min.js"></script>
Expected Output
So the expected output will be more like:
[
{
id: 'c1',
isParent: true,
children: [
{
id: 'c2',
isParent: true,
children: []
},
{
id: 'p1'
isParent: false
}
]
}
]
And so on..
Your code is very imperative. Try focusing on the "big picture" of data flow instead of writing code by trial-and-error. It's harder, but you get better results (and, in fact, usually it's faster) :)
My idea is to first group the categories by their parents. This is the first line of my solution and it actually becomes much easier after that.
_.groupBy and _.keyBy help a lot here:
function makeCatTree(data) {
var groupedByParents = _.groupBy(data, 'parent');
var catsById = _.keyBy(data, 'id');
_.each(_.omit(groupedByParents, ''), function(children, parentId) {
catsById['c' + parentId].children = children;
});
_.each(catsById, function(cat) {
// isParent will be true when there are subcategories (this is not really a good name, btw.)
cat.isParent = !_.isEmpty(cat.children);
// _.compact below is just for removing null posts
cat.children = _.compact(_.union(cat.children, cat.posts));
// optionally, you can also delete cat.posts here.
});
return groupedByParents[''];
}
I recommend trying each part in the developer console, then it becomes easy to understand.
I have made a small fidde that I think that is what you want.
http://jsfiddle.net/tx3uwhke/
var tree = buildTree(getData());
var pre = document.getElementById('a');
var jsonString = JSON.stringify(tree, null, 4);
console.log(jsonString);
pre.innerHTML = jsonString;
document.body.appendChild(pre);
function buildTree(data, parent){
var result = [];
parent = typeof parent !== 'undefined' ? parent : {id:""};
children = _.filter(data, function(value){
return value.parent === parent.id;
});
if(!_.isEmpty(children)){
_.each(children, function(child){
if (child != null){
result.push(child);
if(!_.isEmpty(child.posts)){
var posts = _.filter(child.posts, function(post){
return post !== null && typeof post !== 'undefined';
});
if(!_.isEmpty(posts)){
_.forEach(posts, function(post){
post.isParent = false;
});
}
result = _.union(result, posts);
delete child.posts;
}
ownChildren = buildTree(data, child);
if(!_.isEmpty(ownChildren)){
child.isParent = true;
child.children = ownChildren;
}else{
child.isParent = false;
}
}
});
}
return result;
}
EDIT: made a new fiddle to contain the isParent part you can find it here
While this problem looks simple, I can remember to have struggled achieving it in a simple way. I therefore created a generic util to do so
You only have to write maximum 3 custom callbacks methods.
Here is an example:
import { flattenTreeItemDeep, treeItemFromList } from './tree.util';
import { sortBy } from 'lodash';
const listItems: Array<ListItem> = [
// ordered list arrival
{ id: 1, isFolder: true, parent: null },
{ id: 2, isFolder: true, parent: 1 },
{ id: 3, isFolder: false, parent: 2 },
// unordered arrival
{ id: 4, isFolder: false, parent: 5 },
{ id: 5, isFolder: true, parent: 1 },
// empty main level folder
{ id: 6, isFolder: true, parent: null },
// orphan main level file
{ id: 7, isFolder: false, parent: null },
];
const trees = treeItemFromList(
listItems,
(listItem) => listItem.isFolder, // return true if the listItem contains items
(parent, leafChildren) => parent.id === leafChildren.parent, // return true if the leaf children is contained in the parent
(parent, folderChildren) => parent.id === folderChildren.parent // return true if the children is contained in the parent
);
console.log(trees);
/*
[
{
children: [
{
children: [{ data: { id: 3, isFolder: false, parent: 2 }, isLeaf: true }],
data: { id: 2, isFolder: true, parent: 1 },
isLeaf: false,
},
{
children: [{ data: { id: 4, isFolder: false, parent: 5 }, isLeaf: true }],
data: { id: 5, isFolder: true, parent: 1 },
isLeaf: false,
},
],
data: { id: 1, isFolder: true, parent: null },
isLeaf: false,
},
{ children: [], data: { id: 6, isFolder: true, parent: null }, isLeaf: false },
{
data: {
id: 7,
isFolder: false,
parent: null,
},
isLeaf: true,
},
]
*/
I did not check with your example as all cases are different, you however need to implement only 3 methods to let the algorithm build the tree for you:
If the item is a folder or a leaf (in your case just check if the children contain any non falsy item) i.e. listItem.posts.some((value)=>!!value)
if a parent contains the leaf child, (parent, child) => !!parent.posts.filter((val)=>!!val).find(({id})=>child.id === id)
if a parent contains the folder: optional if this is the same logic as for a leaf child.
I am working on a solution where I need to search for an element in a deeply nested JSON by its id. I have been advised to use underscore.js which I am pretty new to.
After reading the documentation http://underscorejs.org/#find , I tried to implement the solution using find, filter and findWhere.
Here is what I tried using find :
var test = {
"menuInputRequestId": 1,
"catalog":[
{
"uid": 1,
"name": "Pizza",
"desc": "Italian cuisine",
"products": [
{
"uid": 3,
"name": "Devilled chicken",
"desc": "chicken pizza",
"prices":[
{
"uid": 7,
"name": "regular",
"price": "$10"
},
{
"uid": 8,
"name": "large",
"price": "$12"
}
]
}
]
},
{
"uid": 2,
"name": "Pasta",
"desc": "Italian cuisine pasta",
"products": [
{
"uid": 4,
"name": "Lasagne",
"desc": "chicken lasage",
"prices":[
{
"uid": 9,
"name": "small",
"price": "$10"
},
{
"uid": 10,
"name": "large",
"price": "$15"
}
]
},
{
"uid": 5,
"name": "Pasta",
"desc": "chicken pasta",
"prices":[
{
"uid": 11,
"name": "small",
"price": "$8"
},
{
"uid": 12,
"name": "large",
"price": "$12"
}
]
}
]
}
]
};
var x = _.find(test, function (item) {
return item.catalog && item.catalog.uid == 1;
});
And a Fiddle http://jsfiddle.net/8hmz0760/
The issue I faced is that these functions check the top level of the structure and not the nested properties thus returning undefined. I tried to use item.catalog && item.catalog.uid == 1; logic as suggested in a similar question Underscore.js - filtering in a nested Json but failed.
How can I find an item by value by searching the whole deeply nested structure?
EDIT:
The following code is the latest i tried. The issue in that is that it directly traverses to prices nested object and tries to find the value. But my requirement is to search for the value in all the layers of the JSON.
var x = _.filter(test, function(evt) {
return _.any(evt.items, function(itm){
return _.any(itm.outcomes, function(prc) {
return prc.uid === 1 ;
});
});
});
Here's a solution which creates an object where the keys are the uids:
var catalogues = test.catalog;
var products = _.flatten(_.pluck(catalogues, 'products'));
var prices = _.flatten(_.pluck(products, 'prices'));
var ids = _.reduce(catalogues.concat(products,prices), function(memo, value){
memo[value.uid] = value;
return memo;
}, {});
var itemWithUid2 = ids[2]
var itemWithUid12 = ids[12]
I dont use underscore.js but you can use this instead
function isArray(what) {
return Object.prototype.toString.call(what) === '[object Array]';
}
function find(json,key,value){
var result = [];
for (var property in json)
{
//console.log(property);
if (json.hasOwnProperty(property)) {
if( property == key && json[property] == value)
{
result.push(json);
}
if( isArray(json[property]))
{
for(var child in json[property])
{
//console.log(json[property][child]);
var res = find(json[property][child],key,value);
if(res.length >= 1 ){
result.push(res);}
}
}
}
}
return result;
}
console.log(find(test,"uid",4));