Build flat array with levels from tree array in javascript - javascript

I have the following array tree in javascript:
[
{
"id": 1,
"parentId": null,
"description": "Item 1",
"value": 0,
"children": [
{
"id": 2,
"parentId": 1,
"description": "Item 1.1",
"value": 0,
"children": [
{
"id": 3,
"parentId": 2,
"description": "Item 1.1.1",
"value": 0,
"children": []
}
]
}
]
},
{
"id": 4,
"parentId": null,
"description": "Item 2",
"value": 0,
"children": [
{
"id":5,
"parentId": 4,
"description": "Item 2.1",
"value": 0,
"children": []
}
]
}
]
I want to turn it into a flat one with it's levels, like this (see level attribute):
[
{
"id":1,
"parentId": null,
"description":"Item 1",
"value":0,
"level": "1"
},
{
"id":2,
"parentId": 1,
"description":"Item 1.1",
"value":0,
"level": "1.1"
},
{
"id":3,
"parentId": 2,
"description":"Item 1.1.1",
"value":0,
"level": "1.1.1"
},
{
"id":4,
"parentId": null,
"description":"Item 2",
"value":0,
"level": "2"
},
{
"id":5,
"parentId": 4,
"description":"Item 2.1",
"value":0,
"level": "2.1"
}
]
What's the best way to do this regardless of depth?
PS: I have the flat one too, but without "level" attribute and the proposal is to add this attribute based on parentId and sort list by it, like following:
Item 1
Item 1.1
Item 1.1.1
Item 2
Item 2.1

If you don't want to limit the solution by the depth of the array, then I suggest not to use recursion.
const solution = data => {
const stack = data.map((item, index) => ({ ...item, level: `${index + 1}` }))
const result = []
while (stack.length) {
const item = stack.pop()
const { children, ...restItem } = item
stack.push(...item.children.map((child, index) => ({ ...child, level: `${item.level}.${index + 1}` })))
result.push(restItem)
}
return result
}
const data = [
{
"id": 1,
"parentId": null,
"description": "Item 1",
"value": 0,
"children": [
{
"id": 2,
"parentId": 1,
"description": "Item 1.1",
"value": 0,
"children": [
{
"id": 3,
"parentId": 2,
"description": "Item 1.1.1",
"value": 0,
"children": []
}
]
}
]
},
{
"id": 4,
"parentId": null,
"description": "Item 2",
"value": 0,
"children": [
{
"id":5,
"parentId": 4,
"description": "Item 2.1",
"value": 0,
"children": []
}
]
}
]
console.log(solution(data))

If you recursively loop through your array (assuming that children will always be the key), something like this will work.
const arr = [
{
"id": 1,
"parentId": null,
"description": "Item 1",
"value": 0,
"children": [
{
"id": 2,
"parentId": 1,
"description": "Item 1.1",
"value": 0,
"children": [
{
"id": 3,
"parentId": 2,
"description": "Item 1.1.1",
"value": 0,
"children": []
}
]
}
]
},
{
"id": 4,
"parentId": null,
"description": "Item 2",
"value": 0,
"children": [
{
"id":5,
"parentId": 4,
"description": "Item 2.1",
"value": 0,
"children": []
}
]
}
]
const newArray = [];
const flatten = (item, parentIdx) => {
// separate parent from children
item.forEach(({ children, ...child}, idx) => {
// create level
const level = `${parentIdx ? `${parentIdx}.` : ''}${idx + 1}`;
// add parent to new array
newArray.push({...child, level});
// recursively flatten children
flatten(children, level);
})
}
flatten(arr)
console.log(newArray)

Related

Need to add parentId to child in multi-dimensional Array of JSON data

I have a multidimensional array of JSON data with 'n' number of nested children. My task is to add UniqueId to parent JSON and that uniqueId should be added as parentId to the child. Can you please help in javascript. Thanks
Note:
The number of child its recursive, and there can be any number of children. For this purpose, we can have a deep level of three
Input :
[{
"text": 1527978678434,
"value": 1527978678434,
"children": [{
"text": 1292232152442,
"value": 1292232152442,
"children": [{
"text": 474194771845,
"value": 474194771845,
"children": []
},
{
"text": 468086178830,
"value": 468086178830,
"children": []
}
]
},
{
"text": 1067869237589,
"value": 1067869237589,
"children": []
},
{
"text": 1166591731429,
"value": 1166591731429,
"children": []
},
]
}]
The Required Output:
[{
"text": 1527978678434,
"value": 1527978678434,
"parentId": 0,
"uniqueId": 1,
"children": [{
"text": 1292232152442,
"value": 1292232152442,
"parentId": 1,
"uniqueId": 2,
"children": [{
"text": 474194771845,
"value": 474194771845,
"parentId": 2,
"uniqueId": 3,
"children": []
},
{
"text": 468086178830,
"value": 468086178830,
"parentId": 2,
"uniqueId": 4,
"children": []
}
]
},
{
"text": 1067869237589,
"value": 1067869237589,
"parentId": 1,
"uniqueId": 5,
"children": []
},
{
"text": 1166591731429,
"value": 1166591731429,
"parentId": 1,
"uniqueId": 6,
"children": []
},
{
"text": 111221786011,
"value": 111221786011,
"parentId": 1,
"uniqueId": 7,
"children": []
},
{
"text": 641372005975,
"value": 641372005975,
"parentId": 1,
"uniqueId": 8,
"children": [{
"text": 23082640100,
"value": 23082640100,
"parentId": 8,
"uniqueId": 9,
"children": []
}]
}
]
}]
Consider data is your array.
Just do the DFS and alter the data on the fly. + Having a global to hold the increased ID.
let lastUniqueId = 0;
function addIds(children, parentId) {
(children || []).forEach(r => {
r.parentId = parentId;
r.uniqueId = ++lastUniqueId;
addIds(r.children, r.uniqueId);
});
}
addIds(data, lastUniqueId);
This seems something you can do using a recursive function while keeping track of a shared uniqueId counter, assuming the nesting doesn't go incredibly deep:
const data = [{
"text": 1527978678434,
"value": 1527978678434,
"children": [{
"text": 1292232152442,
"value": 1292232152442,
"children": [{
"text": 474194771845,
"value": 474194771845,
"children": []
},
{
"text": 468086178830,
"value": 468086178830,
"children": []
}
]
},
{
"text": 1067869237589,
"value": 1067869237589,
"children": []
},
{
"text": 1166591731429,
"value": 1166591731429,
"children": []
},
]
}];
function convert(array) {
let uniqueId = 0;
function mapData(data, parentId) {
const myId = ++uniqueId;
const result = {
...data, // copy all data
uniqueId, parentId, // add our new fields
// and handle the children recursively
children: data.children.map(c => mapData(c, myId)),
};
// Don't mind this, just tricking JS in displaying the children array at the bottom during console.log
const children = result.children; delete result.children; result.children = children;
return result;
}
return array.map(d => mapData(d, 0));
}
const result = convert(data);
console.log(result);

remove nested null values from javascript array

My javascript array is as below. I want to remove all the null values inside all the children arrays. I managed to remove as below. but i'm looking for more elegant solution other than this
let data = [
{
"id": "359816ba-4bc6-4b7f-b57c-d80331eee0a6",
"name": "organization 1",
"type": "org",
"title": "organization 1",
"children": [
null,
{
"id": "6571cada-490c-41db-97e8-197a9c0faabb",
"name": "location 3",
"org_id": "359816ba-4bc6-4b7f-b57c-d80331eee0a6",
"type": "location",
"title": "location 3",
"children": [
null,
{
"id": "8620fce9-f7d0-442a-86e8-f58e9029a164",
"name": "zone 3",
"zone_settings_id": null,
"location_id": "6571cada-490c-41db-97e8-197a9c0faabb",
"type": "zone",
"title": "zone 3",
"children": [
null,
null,
null
]
},
null,
null
]
},
{
"id": "93b8ad9e-59ee-4de5-ac32-d3d5d19b083c",
"name": "location 4",
"org_id": "359816ba-4bc6-4b7f-b57c-d80331eee0a6",
"type": "location",
"title": "location 4",
"children": [
null,
null,
{
"id": "db14daf4-4488-47fa-8d18-2d213b3a54a5",
"name": "zone 4",
"zone_settings_id": null,
"location_id": "93b8ad9e-59ee-4de5-ac32-d3d5d19b083c",
"type": "zone",
"title": "zone 4",
"children": [
null,
null,
{
"id": "6ae5b04a-1101-4d73-80e4-05d4db454406",
"gwId": "E4956E45107R",
"zone_id": "db14daf4-4488-47fa-8d18-2d213b3a54a5",
"org_id": "359816ba-4bc6-4b7f-b57c-d80331eee0a6",
"title": "E4:95:6E:45:10:7R"
}
]
},
{
"id": "c01398c6-7650-426b-936d-6b88b1b507f2",
"name": "zone 5",
"zone_settings_id": null,
"location_id": "93b8ad9e-59ee-4de5-ac32-d3d5d19b083c",
"type": "zone",
"title": "zone 5",
"children": [
null,
null,
null
]
}
]
},
null
]
},
{
"id": "46665d49-020d-411f-9f11-c9ddad9a741c",
"name": "organization 2",
"type": "org",
"title": "organization 2",
"children": [
null,
null,
null,
null
]
},
{
"id": "95e7d05b-fe67-422d-8617-9f10633ea6f6",
"name": "org 3",
"type": "org",
"title": "org 3",
"children": [
null,
null,
null,
{
"id": "0a8509d8-1fd8-486c-8457-3ff393c09abc",
"name": "location 1 of org 3",
"org_id": "95e7d05b-fe67-422d-8617-9f10633ea6f6",
"type": "location",
"title": "location 1 of org 3",
"children": [
null,
null,
null,
null
]
}
]
}
]
let orgs = data.filter(org => org != null);
orgs.forEach(org => {
org.children = org.children.filter(location => location != null);
})
orgs.forEach(org => {
org.children.forEach(loc => {
loc.children = loc.children.filter(zone => zone != null);
})
})
orgs.forEach(org => {
org.children.forEach(loc => {
loc.children.forEach(zone => {
zone.children = zone.children.filter(router => router != null);
})
})
})
console.log(orgs);
const noNull = array => array
.filter(it => it !== null)
.map(it => it.children ? { ...it, children: noNull(it.children) } : it);
const result = noNull(data);
You could recursively filter the arrays in an immutable way.
Or the mutating version would be:
const noNull = array => {
const result = array.filter(it => it !== null);
for(const value of result)
if(value.children) value.children = noNull(value.children);
return result;
};

How do I flatten a (forest of) trees?

I have a forest of trees of arbitrary height, more or less like this:
let data = [
{ "id": 2, "name": "AAA", "parent_id": null, "short_name": "A" },
{
"id": 10, "name": "BBB", "parent_id": null, "short_name": "B", "children": [
{
"id": 3, "name": "CCC", "parent_id": 10, "short_name": "C", "children": [
{ "id": 6, "name": "DDD", "parent_id": 3, "short_name": "D" },
{ "id": 5, "name": "EEE", "parent_id": 3, "short_name": "E" }
]
},
{
"id": 4, "name": "FFF", "parent_id": 10, "short_name": "F", "children": [
{ "id": 7, "name": "GGG", "parent_id": 4, "short_name": "G" },
{ "id": 8, "name": "HHH", "parent_id": 4, "short_name": "H" }
]
}]
}
];
And I'm trying to produce a representation of all the root-to-leaves paths, something like this
[
[
{
"id": 2,
"name": "AAA"
}
],
[
{
"id": 10,
"name": "B"
},
{
"id": 3,
"name": "C"
},
{
"id": 6,
"name": "DDD"
}
],
[
{
"id": 10,
"name": "B"
},
{
"id": 3,
"name": "C"
},
{
"id": 5,
"name": "EEE"
}
],
[
{
"id": 10,
"name": "B"
},
{
"id": 4,
"name": "F"
},
{
"id": 7,
"name": "GGG"
}
],
[
{
"id": 10,
"name": "B"
},
{
"id": 4,
"name": "F"
},
{
"id": 8,
"name": "HHH"
}
]
]
So I wrote the following code:
function flattenTree(node, path = []) {
if (node.children) {
return node.children.map(child => flattenTree(child, [...path, child]));
} else {
let prefix = path.slice(0, path.length - 1).map(n => ({ id: n.id, name: n.short_name }));
let last = path[path.length - 1];
return [...prefix, { id: last.id, name: last.name } ];
}
}
let paths = data.map(n => flattenTree(n, [n]));
but paths comes out with extra nesting, like this:
[
[
{
"id": 2,
"name": "AAA"
}
],
[
[
[
{
"id": 10,
"name": "B"
},
{
"id": 3,
"name": "C"
},
{
"id": 6,
"name": "DDD"
}
],
[
{
"id": 10,
"name": "B"
},
{
"id": 3,
"name": "C"
},
{
"id": 5,
"name": "EEE"
}
]
],
[
[
{
"id": 10,
"name": "B"
},
{
"id": 4,
"name": "F"
},
{
"id": 7,
"name": "GGG"
}
],
[
{
"id": 10,
"name": "B"
},
{
"id": 4,
"name": "F"
},
{
"id": 8,
"name": "HHH"
}
]
]
]
]
I lost count of the many ways in which I tried to fix this, but it does look like the algorithm should not produce the extra nesting -- or my eyes are just so crossed by now that I couldn't see my mistake if someone stuck their finger on it.
Can someone help? Feel free to peruse this JSFiddle https://jsfiddle.net/png7x9bh/66/
The extra nestings are created by map. map just wraps the results into an array and returns them, it doesn't care if it is called on child nodes or not. Use reduce and just concat (or push, whatever suits your performance) the results into the first level array directly:
let data = [{"id":2,"name":"AAA","parent_id":null,"short_name":"A"},{"id":10,"name":"BBB","parent_id":null,"short_name":"B","children":[{"id":3,"name":"CCC","parent_id":10,"short_name":"C","children":[{"id":6,"name":"DDD","parent_id":3,"short_name":"D"},{"id":5,"name":"EEE","parent_id":3,"short_name":"E"}]},{"id":4,"name":"FFF","parent_id":10,"short_name":"F","children":[{"id":7,"name":"GGG","parent_id":4,"short_name":"G"},{"id":8,"name":"HHH","parent_id":4,"short_name":"H"}]}]}];
function flattenTree(node, path = []) {
let pathCopy = Array.from(path);
pathCopy.push({id: node.id, name: node.name});
if(node.children) {
return node.children.reduce((acc, child) => acc.concat(flattenTree(child, pathCopy)), []);
}
return [pathCopy];
}
let result = data.reduce((result, node) => result.concat(flattenTree(node)), []);
console.log(JSON.stringify(result, null, 3));

Search nested object and return whole path

I have below JavaScript with n level children and want to search for id and if any of item from has matching id than need to return object from root to matching item.
I want to return entire hierarchy of found item from root till object with it's children.
I tried with lodash and underscore and could not find easy solution.
input: {
"children": [{
"name": "Home",
"title": "Home",
"id": "home1",
"children": []
},
{
"name": "BUSINESS AND ROLE SPECIFIC",
"title": "BUSINESS AND ROLE SPECIFIC",
"id": "BAR1",
"children": [{
"name": "Global Businesses",
"title": "Global Businesses",
"id": "GB1",
"children": [{
"name": "Commercial Banking",
"title": "Commercial Banking",
"id": "CB1",
"children": [{
"name": "FLAGSHIP PROGRAMMES",
"title": "FLAGSHIP PROGRAMMES",
"id": "FG1",
"children": []
}]
}]
}]
},
{
"name": "RISK MANAGEMENT",
"title": "RISK MANAGEMENT",
"id": "RM1",
"children": []
}
]
}
Search: {
id: 'FG1'
}
return :{
"name": "BUSINESS AND ROLE SPECIFIC",
"title": "BUSINESS AND ROLE SPECIFIC",
"id": "BAR1",
"children": [{
"name": "Global Businesses",
"title": "Global Businesses",
"id": "GB1",
"children": [{
"name": "Commercial Banking",
"title": "Commercial Banking",
"id": "CB1",
"children": [{
"name": "FLAGSHIP PROGRAMMES",
"title": "FLAGSHIP PROGRAMMES",
"id": "FG1",
"children": [{}]
}]
}]
}]
}
You could use this function:
function findChild(obj, condition) {
if (Object.entries(condition).every( ([k,v]) => obj[k] === v )) {
return obj;
}
for (const child of obj.children || []) {
const found = findChild(child, condition);
// If found, then add this node to the ancestors of the result
if (found) return Object.assign({}, obj, { children: [found] });
}
}
// Sample data
var input = { "children": [{ "name": "Home", "title": "Home", "id": "home1", "children": [] }, { "name": "BUSINESS AND ROLE SPECIFIC", "title": "BUSINESS AND ROLE SPECIFIC", "id": "BAR1", "children": [{ "name": "Global Businesses", "title": "Global Businesses", "id": "GB1", "children": [{ "name": "Commercial Banking", "title": "Commercial Banking", "id": "CB1", "children": [{ "name": "FLAGSHIP PROGRAMMES", "title": "FLAGSHIP PROGRAMMES", "id": "FG1", "children": [] }] }] }] }, { "name": "RISK MANAGEMENT", "title": "RISK MANAGEMENT", "id": "RM1", "children": [] } ]},
search = { id: 'FG1' };
console.log(findChild(input, search));
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use this also for searching with multiple conditions, which must be true at the same time:
search = { "name": "Global Businesses", "title": "Global Businesses" };
... would give you the object that has the specified name and title.
Follow-up question
You asked in comments:
Is there way to supply number to not remove children for given node in input. like,
const donotRemoveChildNode = 2;
console.log(findChild(input, search, donotRemoveChildNode ));
...so it will not remove that specific node's children if it matches condition?
Here, if we search for { id: 'FG1'} and supply donotRemoveChildNode = 2, it would not remove the first level children for "Commercial banking".
I would say the donotRemoveChildNode would have to be 3, as there are three levels of children arrays in the ancestor-hierarchy of the "Commercial banking" node. A value of 0 would show the first level children of the top-most children property.
Here is how that extra argument would work -- I added some records to the data to illustrate the difference in the output:
function findChild(obj, condition, removeChildNodesBefore = Infinity) {
if (Object.entries(condition).every( ([k,v]) => obj[k] === v )) {
return obj;
}
for (const child of obj.children || []) {
let found = findChild(child, condition, removeChildNodesBefore - 1);
if (found) {
return Object.assign({}, obj, {
children: removeChildNodesBefore <= 0
? obj.children.map( sibling =>
sibling == child ? found
: Object.assign({}, sibling, {children: []})
)
: [found]
});
}
}
}
var input = { "children": [{ "name": "Home", "title": "Home", "id": "home1", "children": [] }, { "name": "BUSINESS AND ROLE SPECIFIC", "title": "BUSINESS AND ROLE SPECIFIC", "id": "BAR1", "children": [{ "name": "Global Businesses", "title": "Global Businesses", "id": "GB1", "children": [{ "name": "test", "title": "test", "id": "xxx", "children": [{ "name": "testDeep", "title": "test", "id": "deep", "children": []}]}, { "name": "Commercial Banking", "title": "Commercial Banking", "id": "CB1", "children": [{ "name": "test", "title": "test", "id": "yyy", "children": []}, { "name": "FLAGSHIP PROGRAMMES", "title": "FLAGSHIP PROGRAMMES", "id": "FG1", "children": [] }] }] }] }, { "name": "RISK MANAGEMENT", "title": "RISK MANAGEMENT", "id": "RM1", "children": [] } ]},
search = { id: 'FG1' }
console.log(findChild(input, search, 3));
.as-console-wrapper { max-height: 100% !important; top: 0; }
function getBranch(branches, leaf_id)
{
var result_branch = null;
branches.some(function(branch, idx) {
if (branch.id == leaf_id) {
result_branch = Object.assign({}, branch);
result_branch.children.forEach(function(child, idx) {
delete result_branch.children[idx].children;
});
return true;
} else {
let target_branch = getBranch(branch.children, leaf_id);
if (target_branch) {
result_branch = Object.assign({}, branch);
delete result_branch.children
result_branch.children = [target_branch];
return true;
}
}
return false;
});
return result_branch;
}
console.log(getBranch(input.children, 'GB1'));
One way is to first loop the root children, and then create another function to see if the Id exists in any of it's children.
var data = {
"children": [{
"name": "Home",
"title": "Home",
"id": "home1",
"children": []
},
{
"name": "BUSINESS AND ROLE SPECIFIC",
"title": "BUSINESS AND ROLE SPECIFIC",
"id": "BAR1",
"children": [{
"name": "Global Businesses",
"title": "Global Businesses",
"id": "GB1",
"children": [{
"name": "Commercial Banking",
"title": "Commercial Banking",
"id": "CB1",
"children": [{
"name": "FLAGSHIP PROGRAMMES",
"title": "FLAGSHIP PROGRAMMES",
"id": "FG1",
"children": []
}]
}]
}]
},
{
"name": "RISK MANAGEMENT",
"title": "RISK MANAGEMENT",
"id": "RM1",
"children": []
}
]
};
function hasId( id, data ) {
if (data.id === id) return true;
if (data.children) {
for (const child of data.children) {
if (hasId( id, child)) return true;
}
}
return false;
}
function search( id, data ) {
for (const child of data.children) {
if (hasId(id, child)) return child;
}
return null;
}
console.log(search( "FG1", data ));

Javascript sum of items in a complex object

I have some data that I'm counting and putting the totals into an array.
Here is the data and code:
var data = {
"cars": [
{
"id": "1",
"name": "name 1",
"thsub": [
{
"id": "11",
"name": "sub 1",
"stats": {
"items": 5,
},
"ions": null
},
{
"id": "22",
"name": "sub 2",
"stats": {
"items": 5,
},
"translations": null
}
],
"image": null
},
{
"id": "2",
"name": "name 2",
"thsub": [
{
"id": "33",
"name": "sub 43",
"stats": {
"items": 20,
},
"ions": null
},
{
"id": "44",
"name": "sub 76",
"stats": {
"items": 5,
},
"translations": null
}
],
"image": null
}
]
}
var thCount = [];
for(key in data.cars[0].thsub ){
if(data.cars[0].thsub[key].stats){
thCount.push(data.cars[0].thsub[key].stats.items);
}
}
console.log(thCount);
For some reason "thCount" is returning [5, 5] when the result should be: [10, 25]
where is the code going wrong?
The correct code for your problem is as pasted below:
**var count = [];
for(var i = 0; i < data.cars.length; i++){
countSum = 0;
for(key in data.cars[i].thsub){
countSum = countSum + data.cars[i].thsub[key].stats.items;
}
count.push(countSum);
}**
Try this code, will solve your problem.
You need another loop on cars.
var data = {
"cars": [{
"id": "1",
"name": "name 1",
"thsub": [{
"id": "11",
"name": "sub 1",
"stats": {
"items": 5,
},
"ions": null
}, {
"id": "22",
"name": "sub 2",
"stats": {
"items": 5,
},
"translations": null
}],
"image": null
},
{
"id": "2",
"name": "name 2",
"thsub": [{
"id": "33",
"name": "sub 43",
"stats": {
"items": 20,
},
"ions": null
}, {
"id": "44",
"name": "sub 76",
"stats": {
"items": 5,
},
"translations": null
}],
"image": null
}
]
}
var thCount = [];
for (var l = 0, m = data.cars.length; l < m; l++) {
thCount[l] = 0;
for (var i = 0, j = data.cars[l].thsub.length; i < j; i++) {
if (data.cars[l].thsub[i].stats) {
thCount[l]+=data.cars[l].thsub[i].stats.items;
}
}
}
console.log(thCount);
You should use reduce() and map() methods.Any of this using a callback function.
The reduce() method applies a function against an accumulator and each
value of the array (from left-to-right) to reduce it to a single
value.
The map() method creates a new array with the results of calling a
provided function on every element in this array.
var result=data.cars.map(function(item){
return item.thsub.reduce(function(a, b) { return a.stats.items + b.stats.items; });
});
var data = {
"cars": [
{
"id": "1",
"name": "name 1",
"thsub": [
{
"id": "11",
"name": "sub 1",
"stats": {
"items": 5,
},
"ions": null
},
{
"id": "22",
"name": "sub 2",
"stats": {
"items": 5,
},
"translations": null
}
],
"image": null
},
{
"id": "2",
"name": "name 2",
"thsub": [
{
"id": "33",
"name": "sub 43",
"stats": {
"items": 20,
},
"ions": null
},
{
"id": "44",
"name": "sub 76",
"stats": {
"items": 5,
},
"translations": null
}
],
"image": null
}
]
}
console.log(data.cars.map(function(item){
return item.thsub.reduce(function(a, b) { return a.stats.items + b.stats.items; });
}));

Categories

Resources