Find the parent of the searched value using javascript - javascript

I have a JSON data in the following format which needs to be filtered based on a specific value :
[
{
"id": 0,
"name": "ROOT-0",
"childs": [
{
"id": 1,
"name": "ROOT-1",
"childs": [
{
"id": 11,
"name": "ROOT-11",
},
{
"id": 12,
"name": "ROOT-12",
},
]
},
{
"id": 2,
"name": "ROOT-2",
"childs": [
{
"id": 21,
"name": "ROOT-21",
},
{
"id": 22,
"name": "ROOT-22",
},
]
},
{
"id": 3,
"name": "ROOT-3",
"childs": [
{
"id": 31,
"name": "ROOT-31",
},
{
"id": 32,
"name": "ROOT-32",
},
]
}
]
}]
The scenario is that I need to get ROOT-1 as final result if I look for ROOT-11/ROOT-12.
I have tried filtering with this following code
var res = data[0].filter(function f(o) {
if (o.name.includes("ROOT-11")) return o;
})
But I am not able to get a grip on the logic. Is there a way to achieve my desired output

You could use find()...
var result = data[0].childs.find(x => {
return x.childs.find(y => {
return y.name === name;
});
}).name;
Or you could write a function...
function findParentName(name, data) {
return data[0].childs.find(x => {
return x.childs.find(y => {
return y.name === name;
});
}).name;
}
var result = findParentName('ROOT-11', data);
console.log(result);
Doing this will give you the best performance result as find() will return as soon as it finds a match, and not iterate through each remaining loop like forEach() or map()
If you're using ES6 you can say...
const result = data[0].childs.find(x => x.childs.find(y => y.name === 'ROOT-11')).name;

You can grab the item using a few filters and a find, to get the result you are looking for:
let items = [{
"id": 0,
"name": "ROOT-0",
"childs": [{
"id": 1,
"name": "ROOT-1",
"childs": [{
"id": 11,
"name": "ROOT-11",
},
{
"id": 12,
"name": "ROOT-12",
},
]
},
{
"id": 2,
"name": "ROOT-2",
"childs": [{
"id": 21,
"name": "ROOT-21",
},
{
"id": 22,
"name": "ROOT-22",
},
]
},
{
"id": 3,
"name": "ROOT-3",
"childs": [{
"id": 31,
"name": "ROOT-31",
},
{
"id": 32,
"name": "ROOT-32",
},
]
}
]
}]
function find(name) {
let result
items.filter(item =>
result = item.childs.find(item2 =>
item2.childs.filter(i => i.name == name).length > 0
)
)
return result.name || ''
}
console.log(find('ROOT-11'))
console.log(find('ROOT-22'))
console.log(find('ROOT-32'))

You could, for an arbitrary count nested children, use a recusion approach by iterating the actual level and if not found check the children with the actual name.
If the wanted name is found, the parent's name is handed over through all nested calls and returned.
function getParent(array, search, parent) {
return array.some(o => o.name === search || o.children && (parent = getParent(o.children, search, o.name)))
&& parent;
}
var data = [{ id: 0, name: "ROOT-0", children: [{ id: 1, name: "ROOT-1", children: [{ id: 11, name: "ROOT-11" }, { id: 12, name: "ROOT-12" }] }, { id: 2, name: "ROOT-2", children: [{ id: 21, name: "ROOT-21" }, { id: 22, name: "ROOT-22" }] }, { id: 3, name: "ROOT-3", children: [{ id: 31, name: "ROOT-31" }, { id: 32, name: "ROOT-32" }] }] }]
console.log(getParent(data, 'ROOT-0')); // undefined no parent found
console.log(getParent(data, 'ROOT-1')); // ROOT-0
console.log(getParent(data, 'ROOT-11')); // ROOT-1
console.log(getParent(data, 'ROOT-31')); // ROOT-3
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related

How to get immediate parent Id of the child id in array of nested json Object?

I need to get the parent id of the specific child.
Here is my sample JSON, If I give entity id 32 it should return 6 as parent Id and if I give 30 it should return 5 as parent id.
const arr = [{
"id": 0,
"name": "My Entity",
"children": [
{
"id": 1,
"name": "MARKET",
"children": [
{
"id": 2,
"name": "Sales",
"children": [
{
"id": 3,
"name": "District 1",
"children": [
{
"id": 5,
"name": "Area 1",
"children": [
{
"entityId": 30,
"id": 26,
"name": "Mumbai"
},
{
"entityId": 31,
"id": 26,
"name": "Hyderabad"
}
],
"num": 0,
},
{
"id": 6,
"name": "Area 2",
"children": [
{
"entityId": 32,
"id": 32,
"name": "Karnataka"
},
{
"entityId": 33,
"id": 33,
"name": "Andhra Pradesh"
}
],
"num": 0,
},
]
},
]
},
]
},
]
}]
Here is the code I have tried
const findParent = (arr, entityId) => {
for (let i = 0; i < arr.length; i++) {
if (arr[i].entityId === entityId) {
return [];
} else if (arr[i].children && arr[i].children.length) {
const t = findParents(arr[i].children, entityId);
if (t !== false) {
t.push(arr[i].id);
return t;
}
}
}
return false;
};
findParents(arr, 30);
But it is returning like below
[
5,
3,
2,
1,
0
]
But I want the output to be
[
5
]
Kindly help me on this, thanks
Replace this:
t.push(arr[i].id);
with:
if (t.length == 0) t.push(arr[i].id);
I would suggest easier solution
const findParent = (arr, entityId) => {
const children = arr.flatMap(parent =>
(item.children || []).map(child => ({ parent, child, entityId: child.entityId }))
)
const res = children.find(item => item.entityId === entityId)
return res.entityId || findChildren(res.map(v => v.child), entityId)
}

Find object by specific key in a deep nested object | Javascript

What is the cleanest way to find object and return that based on id , If I don't know how many nested object there will be in my object ?
Let's say I have the following structure :
myObj = {
"id": "5e6b8961ba08180001a10bb6",
"children": [
{
"id": "5e6b8961ba08180001a10bb7",
"refrenceId": "SEC-02986",
"children": [
{
"id": "5e58d7bc1bbc71000118c0dc"
},
{
"id": "5e58d7bc1bbc71000118c0dd",
"refrenceId": "SKU-00343"
},
{
"id": "5e590d571bbc71000118c102",
"refrenceId": "SKU-05290"
},
{
"id": "5e590df71bbc71000118c109",
"children": [
{
"id": "5e590df71bbc71000118c10a"
},
{
"id": "5e590df71bbc71000118c10b",
"refrenceId": "SKU-00444"
},
{
"id": "5e5cb9428ae591000177c0f6"
}
]
},
{
"id": "5e81899f0bab450001dcfc1d",
"refrenceId": "SEC-03260"
},
{
"id": "5e81c4b51503860001f97f6c",
"refrenceId": "SEC-03267",
"children": [
{
"id": "5e8ad5175d374200014edb3a",
"refrenceId": "SEC-03409",
"children": [
{
"id": "5e8f28882d94c1000156bebe"
}
]
},
{
"id": "5e8ad5175d374200014edb3c",
"refrenceId": "SEC-03410"
},
{
"id": "5e8f29082d94c1000156bec6",
"refrenceId": "SEC-03495"
}
]
}
]
}
Suppose, I want to find the one with id "5e590df71bbc71000118c10b", and return that object from nested object.
I have tried using following code:
function nodeHasChildren(children, id) {
for (const child of children) {
if (child.id === id) {
if (Array.isArray(child.children) && child.children.length > 0) {
return child;
}
}
else {
const result = nodeHasChildren(child.children, id);
if (result !== undefined) {
return result
}
}
}
}
console.log(nodeWithIdHasChildren(myObj, "5e590df71bbc71000118c10b"));
Use simple recursion
function findDeepById(node, id) {
if (node.id === id) return node;
if (node.children) {
for(const child of node.children){
const match = findDeepById(child, id);
if (match) return match;
}
}
}
const myObj = {
"id": "5e6b8961ba08180001a10bb6",
"children": [{
"id": "5e6b8961ba08180001a10bb7",
"refrenceId": "SEC-02986",
"children": [{
"id": "5e58d7bc1bbc71000118c0dc"
},
{
"id": "5e58d7bc1bbc71000118c0dd",
"refrenceId": "SKU-00343"
},
{
"id": "5e590d571bbc71000118c102",
"refrenceId": "SKU-05290"
},
{
"id": "5e590df71bbc71000118c109",
"children": [{
"id": "5e590df71bbc71000118c10a"
},
{
"id": "5e590df71bbc71000118c10b",
"refrenceId": "SKU-00444"
},
{
"id": "5e5cb9428ae591000177c0f6"
}
]
},
{
"id": "5e81899f0bab450001dcfc1d",
"refrenceId": "SEC-03260"
},
{
"id": "5e81c4b51503860001f97f6c",
"refrenceId": "SEC-03267",
"children": [{
"id": "5e8ad5175d374200014edb3a",
"refrenceId": "SEC-03409",
"children": [{
"id": "5e8f28882d94c1000156bebe"
}]
},
{
"id": "5e8ad5175d374200014edb3c",
"refrenceId": "SEC-03410"
},
{
"id": "5e8f29082d94c1000156bec6",
"refrenceId": "SEC-03495"
}
]
}
]
}]
};
function findDeepById(node, id) {
if (node.id === id) return node;
if (node.children) {
for(const child of node.children){
const match = findDeepById(child, id);
if (match) return match;
}
}
}
console.log(findDeepById(myObj, "5e590df71bbc71000118c10b"));
In short, this part was the biggest problem:
if (child.id === id) {
if (Array.isArray(child.children) && child.children.length > 0) {
return child;
}
}
You've found your object, why look for its children?
ORIGINAL ANSWER/WORKING SOLUTION
For start, you need to make your original object iterable because that's what your function expects, I've done so by simply making it an array like nodeHasChildren([myObj], ... when calling the function. Then, after some cleanup and fixing the logic mentioned above, we get this (added relevant comments to the code below):
myObj = {
"id": "5e6b8961ba08180001a10bb6",
"children": [{
"id": "5e6b8961ba08180001a10bb7",
"refrenceId": "SEC-02986",
"children": [{
"id": "5e58d7bc1bbc71000118c0dc"
},
{
"id": "5e58d7bc1bbc71000118c0dd",
"refrenceId": "SKU-00343"
},
{
"id": "5e590d571bbc71000118c102",
"refrenceId": "SKU-05290"
},
{
"id": "5e590df71bbc71000118c109",
"children": [{
"id": "5e590df71bbc71000118c10a"
},
{
"id": "5e590df71bbc71000118c10b",
"refrenceId": "SKU-00444"
},
{
"id": "5e5cb9428ae591000177c0f6"
}
]
},
{
"id": "5e81899f0bab450001dcfc1d",
"refrenceId": "SEC-03260"
},
{
"id": "5e81c4b51503860001f97f6c",
"refrenceId": "SEC-03267",
"children": [{
"id": "5e8ad5175d374200014edb3a",
"refrenceId": "SEC-03409",
"children": [{
"id": "5e8f28882d94c1000156bebe"
}]
},
{
"id": "5e8ad5175d374200014edb3c",
"refrenceId": "SEC-03410"
},
{
"id": "5e8f29082d94c1000156bec6",
"refrenceId": "SEC-03495"
}
]
}
]
}]
}
function nodeHasChildren(children, id) {
for (const child of children) {
if (child.id === id) {
// solution found, no need to do anything else
console.log("SOLUTION: ");
return child;
} else {
// check if it has children and iterate over them recursively
if (Array.isArray(child.children) && child.children.length > 0)
var result = nodeHasChildren(child.children, id);
// check if the result was found in children in the line above
if (result != undefined)
return result;
}
}
}
console.log(nodeHasChildren([myObj], "5e590df71bbc71000118c10b"));
console.log(nodeHasChildren([myObj], "5e8ad5175d374200014edb3c"));
We now use object-scan for simple data processing tasks. It's pretty awesome once you wrap your head around it. Here is how you could answer your questions
// const objectScan = require('object-scan');
const find = (id, input) => objectScan(['**'], {
rtn: 'value',
abort: true,
filterFn: ({ value }) => value.id === id
})(input);
const myObj = { id: '5e6b8961ba08180001a10bb6', children: [{ id: '5e6b8961ba08180001a10bb7', refrenceId: 'SEC-02986', children: [{ id: '5e58d7bc1bbc71000118c0dc' }, { id: '5e58d7bc1bbc71000118c0dd', refrenceId: 'SKU-00343' }, { id: '5e590d571bbc71000118c102', refrenceId: 'SKU-05290' }, { id: '5e590df71bbc71000118c109', children: [{ id: '5e590df71bbc71000118c10a' }, { id: '5e590df71bbc71000118c10b', refrenceId: 'SKU-00444' }, { id: '5e5cb9428ae591000177c0f6' }] }, { id: '5e81899f0bab450001dcfc1d', refrenceId: 'SEC-03260' }, { id: '5e81c4b51503860001f97f6c', refrenceId: 'SEC-03267', children: [{ id: '5e8ad5175d374200014edb3a', refrenceId: 'SEC-03409', children: [{ id: '5e8f28882d94c1000156bebe' }] }, { id: '5e8ad5175d374200014edb3c', refrenceId: 'SEC-03410' }, { id: '5e8f29082d94c1000156bec6', refrenceId: 'SEC-03495' }] }] }] };
console.log(find('5e8ad5175d374200014edb3a', myObj));
/* =>
{ id: '5e8ad5175d374200014edb3a',
refrenceId: 'SEC-03409',
children: [ { id: '5e8f28882d94c1000156bebe' } ] }
*/
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#13.8.0"></script>
Disclaimer: I'm the author of object-scan

Making one to many relation array in JavaScript

I have two arrays of objects:
var a = [{
"id": 1,
"name": "q"
},
{
"id": 2,
"name": "l"
}]
and another is
var b = [{
"id": 3,
"sub": 1,
"name": "ni"
},
{
"id": 4,
"sub": 2,
"name": "bh"
}]
Here sub is the id in a
I need to have a new array which will look like this:
var c = [
{
"id":1,
"name":"q",
"map":[
{
"id":3,
"name":"ni"
}
]
},
{
"id":2,
"name":"l",
"map":[
{
"id":4,
"name":"bh"
}
]
}
]
How can I do that in JavaScript?
I am using underscore in my project.
In plain Javascript you could use Array#map, Array#forEach and a hash table.
var a = [{ "id": 1, "name": "q" }, { "id": 2, "name": "l" }],
b = [{ "id": 3, "sub": 1, "name": "ni" }, { "id": 4, "sub": 2, "name": "bh" }],
hash = Object.create(null),
result = a.map(function (a, i) {
hash[a.id] = { id: a.id, name: a.name };
return hash[a.id];
}, hash);
b.forEach(function (a) {
hash[a.sub].map = hash[a.sub].map || [];
hash[a.sub].map.push({ id: a.id, name: a.name });
}, hash);
console.log(result);
ES6
var a = [{ "id": 1, "name": "q" }, { "id": 2, "name": "l" }],
b = [{ "id": 3, "sub": 1, "name": "ni" }, { "id": 4, "sub": 2, "name": "bh" }],
hash = Object.create(null),
result = a.map((hash => a => hash[a.id] = { id: a.id, name: a.name, map: [] })(hash));
b.forEach((hash => a => hash[a.sub].map.push({ id: a.id, name: a.name }))(hash));
console.log(result);
You can do it with the help of map function and then use the find function to search the data from the other array.
var b = [{
"id": 3,
"sub": 1,
"name": "ni"
}, {
"id": 4,
"sub": 2,
"name": "bh"
}];
var a = [{
"id": 1,
"name": "q"
}, {
"id": 2,
"name": "l"
}];
var final = _.map(b, function(d) {
return {
id: d.name,
name: d.name,
map: _.find(a, function(adata) {
return adata.id == d.sub; //use underscore find to get the relevant data from array a
})
}
});
console.log(final);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

lodash merge and combine objects

I have an array of objects as below that I read from my database using sequelize ORM:
I want to have all my videos from a section, but the better I can return using sequelize is :
[{
"id": 2,
"name": "Ru",
"subsection": 1,
"Video": {
"id": 11,
"source": "sourrrccrsss22222",
"videoSubSection": 2
}
},
{
"id": 2,
"name": "Ru",
"subsection": 1,
"Video": {
"id": 12,
"source": "sourrrccrsss111",
"videoSubSection": 2
}
},
{
"id": 1,
"name": "Oc",
"subsection": 1,
"Video": {
"id": 13,
"source": "sourrrcc",
"videoSubSection": 1
}
},
{
"id": 1,
"name": "Oc",
"subsection": 1,
"Video": {
"id": 14,
"source": "sourrrcc",
"videoSubSection": 1
}
}]
Is there a way to merge and combine the objects in my array to obtain something like this :
[{
"id": 2,
"name": "Ru",
"subsection": 1,
"Video": [{
"id": 11,
"source": "sourrrccrsss22222",
"videoSubSection": 2
},{
"id": 12,
"source": "sourrrccrsss111",
"videoSubSection": 2
}]
},
{
"id": 1,
"name": "Oc",
"subsection": 1,
"Video": [{
"id": 13,
"source": "sourrrcc",
"videoSubSection": 1
},{
"id": 14,
"source": "sourrrcc",
"videoSubSection": 1
}]
}
The function that approach the most is _.mergeWith(object, sources, customizer) but the main problem I have is that I have on object and need to merge this object.
In plain Javascript, you can use Array#forEach() with a temporary object for the arrays.
var data = [{ id: 2, name: "Ru", subsection: 1, Video: { id: 11, source: "sourrrccrsss22222", VideoSubSection: 2 } }, { id: 2, name: "Ru", subsection: 1, Video: { id: 12, source: "sourrrccrsss111", VideoSubSection: 2 } }, { id: 1, name: "Oc", subsection: 1, Video: { id: 13, source: "sourrrcc", VideoSubSection: 1 } }, { id: 1, name: "Oc", subsection: 1, Video: { id: 14, source: "sourrrcc", VideoSubSection: 1 } }],
merged = function (data) {
var r = [], o = {};
data.forEach(function (a) {
if (!(a.id in o)) {
o[a.id] = [];
r.push({ id: a.id, name: a.name, subsection: a.subsection, Video: o[a.id] });
}
o[a.id].push(a.Video);
});
return r;
}(data);
document.write('<pre>' + JSON.stringify(merged, 0, 4) + '</pre>');
Maybe try transform():
_.transform(data, (result, item) => {
let found;
if ((found = _.find(result, { id: item.id }))) {
found.Video.push(item.Video);
} else {
result.push(_.defaults({ Video: [ item.Video ] }, item));
}
}, []);
Using reduce() would work here as well, but transform() is less verbose.
You can do it this way (test is your db output here)
var result = [];
var map = [];
_.forEach(test, (o) => {
var temp = _.clone(o);
delete o.Video;
if (!_.some(map, o)) {
result.push(_.extend(o, {Video: [temp.Video]}));
map.push(o);
} else {
var index = _.findIndex(map, o);
result[index].Video.push(temp.Video);
}
});
console.log(result); // outputs what you want.

Nested Tree structure object trying to extract and get information Json object

I would like to know the correct way to create a nested Json tree Structure object in javascript.
data structure containing objects and arrays. How can I extract the information, i.e. access a specific or multiple values (or id)?
I have a very deep nested tree structure Json and I am given an object that can exist at any depth. I need to be able to iterate through all grandparent / parent / children nodes until I find the requested category, plus be able to capture its grandparent / parent / children categories all the way through.
//input data structure
[{
"Type": "grdparent1",
"name": "grdparent1",
"children": [{
"Type": "grdparent1",
"Id": 45,
"children": []
}, {
"Type": "grdparent1",
"Id": 46,
"children": [{
"Type": "parent1",
"Id": 54,
"children": [{
"Type": "child1",
"Id": 63,
"children": []
}, {
"Type": "child2",
"Id": 64,
"children": []
}]
}, {
"Type": "parent2",
"Id": 57,
"children": []
}]
}]
}, {
"Type": "grdparent2",
"name": "grdparent2",
"children": [{
"Type": "grdparent2",
"Id": 4,
"children": [{
"Type": "parent1",
"Id": 16,
"children": [{
"children": [],
"Type": "child1",
"Id": 28,
}]
}, {
"Type": "parent2",
"Id": 17,
"children": []
}]
}]
}, {
"Type": "grdparent3",
"name": "grdparent3",
"children": []
}, {
"Type": "grdparent4",
"name": "grdparent4",
"children": [{
"Type": "parent1",
"Id": 167,
"children": []
}]
}]
//output
[{
"grdparent1": [{
"Id": 45,
}, {
"Id": 46,
"parent1": [{
"Id": 54,
"child1": {
"Id": 63
}
}, {
"child2": {
"Id": 64
}
}]
}, {
"parent2": [{
"Id": 57
}]
}]
}, {
"grdparent2": [{
"Id": 4,
"parent1": [{
"Id": 16,
"child1": [{
"Id": 28
}]
}, {
"parent2": [{
"Id": 17
}]
}]
}, {
"grdparent4": [{
"parent1": [{
"Id": 167
}]
}]
}]
}]
Here is the code. You have the result in output variable:
var input = [{
"Type": "grdparent1",
"name": "grdparent1",
"children": [{
"Type": "grdparent1",
"Id": 45,
"children": []
}, {
"Type": "grdparent1",
"Id": 46,
"children": [{
"Type": "parent1",
"Id": 54,
"children": [{
"Type": "child1",
"Id": 63,
"children": []
}, {
"Type": "child2",
"Id": 64,
"children": []
}]
}, {
"Type": "parent2",
"Id": 57,
"children": []
}]
}]
}, {
"Type": "grdparent2",
"name": "grdparent2",
"children": [{
"Type": "grdparent2",
"Id": 4,
"children": [{
"Type": "parent1",
"Id": 16,
"children": [{
"children": [],
"Type": "child1",
"Id": 28,
}]
}, {
"Type": "parent2",
"Id": 17,
"children": []
}]
}]
}, {
"Type": "grdparent3",
"name": "grdparent3",
"children": []
}, {
"Type": "grdparent4",
"name": "grdparent4",
"children": [{
"Type": "parent1",
"Id": 167,
"children": []
}]
}];
var output = [];
for(var index = 0; index < input.length; index++) {
if(input[index].children.length > 0) {
var parsedObject = parseTopLevelItem(input[index]);
if(parsedObject) {
output[output.length] = parsedObject;
}
}
}
alert(JSON.stringify(output));
function parseTopLevelItem(item) {
var topLevelReturnObject;
if(item.children.length > 0) {
topLevelReturnObject = {};
for(var i = 0; i < item.children.length; i++) {
var parsedObject = parseChild(item.children[i]);
if(parsedObject) {
var key = parsedObject[0];
if(!topLevelReturnObject[key]) {
topLevelReturnObject[key] = [];
}
topLevelReturnObject[key][(topLevelReturnObject[key]).length] = parsedObject[1];
}
}
}
return topLevelReturnObject;
}
function parseChild(childElement){
var returnObject = [];
returnObject[0] = childElement.Type;
returnObject[1] = {};
returnObject[1].Id = childElement.Id;
for(var i = 0; i < childElement.children.length; i++) {
var parsedObject = parseChild(childElement.children[i]);
if(parsedObject) {
var key = parsedObject[0];
if(!returnObject[1][key]) {
returnObject[1][key] = [];
}
returnObject[1][key][(returnObject[1][key]).length] = parsedObject[1];
}
}
return returnObject;
}
As this has been brought back up...
Here's an approach which uses some fairly standard utility functions to allow for a fairly simple implementation of your node reformatting and wraps that in a simple transformation of your whole forest of nodes. (It's not a tree, precisely, as there isn't a single root. This is commonly called a "forest".)
// utility functions
const groupBy = (fn) => (xs) =>
xs .reduce ((a, x) => ({... a, [fn(x)]: [... (a [fn (x)] || []), x]}), {})
const mapObject = (fn) => (obj) =>
Object .fromEntries (Object .entries (obj) .map (([k, v]) => [k, fn(v)]))
// helper functions
const hasKids = ({children = []}) => children .length > 0
const hasGrandkids = ({children = []}) => children .some (hasKids)
// main functions
const reformat = ({Id, children = []}) => ({
...(Id ? {Id} : {}),
... mapObject (kids => kids .map (reformat)) (groupBy (o => o.Type) (children))
})
const transform = (nodes) =>
nodes .filter (hasGrandkids) .map (reformat)
// sample data
const input = [{Type: "grdparent1", name: "grdparent1", children: [{Type: "grdparent1", Id: 45, children: []}, {Type: "grdparent1", Id: 46, children: [{Type: "parent1", Id: 54, children: [{Type: "child1", Id: 63, children: []}, {Type: "child2", Id: 64, children: []}]}, {Type: "parent2", Id: 57, children: []}]}]}, {Type: "grdparent2", name: "grdparent2", children: [{Type: "grdparent2", Id: 4, children: [{Type: "parent1", Id: 16, children: [{children: [], Type: "child1", Id: 28}]}, {Type: "parent2", Id: 17, children: []}]}]}, {Type: "grdparent3", name: "grdparent3", children: []}, {Type: "grdparent4", name: "grdparent4", children: [{Type: "parent1", Id: 167, children: []}]}]
// demo
console .log (transform (input))
.as-console-wrapper {max-height: 100% !important; top: 0}
The two important utility functions used are
groupBy which groups an array into an object where the keys are generated by the supplied function mapped against the elements, and the values are arrays of the elements that generated that key. That is, for example,
groupBy (({name}) => name[0]) ([
{name: 'alice', age: 26},
{name: 'bob', age: 19},
{name: 'andrew', age: 31},
{name: 'carol', age: 22}
])
//=>
// {
// a: [{name: 'alice', age: 26}, {name: 'andrew', age: 31}],
// b: [{name: 'bob', age: 19}],
// c: [{name: 'carol', age: 22}]
// }
and mapObject, which maps a function over the values of an object, for example,
mapObject (n => n * n) ({a: 2, b: 3, c: 5, d: 7})
//=> {a: 1, b: 4, c: 25, d: 49}
We also have two helper functions which simply determine whether the node has children and whether it has grandchildren. We will use this in transform, to choose only those nodes with grandchildren. And that, in fact, is all transform does: it filters the list of nodes to include only those with grandchildren, and then it calls our reformat function on each of them. (It's not at all clear to me that this is what was desired in the first place. The question title and text refer to searching for nodes, but there is no evidence in any code of actual searching taking place. I'm guessing here in a way that matches the sample output and at least one other answer. This part would be easy enough to refactor.)
reformat is the main function here, formatting a node and recurring on each of its children. This is a fairly tricky reformat, turning child Type names into object keys and including Id in the output only when it's present in the input.
But the code isn't that complex, thanks to the use of the two helper functions. We group the children by their Type property, and then on the resulting object, we use mapObject to apply kids => kids .map (reformat) to each node.
groupBy and mapObject are general-purpose utility functions, and there are equivalents in major libraries like Underscore, Lodash, and Ramda (disclaimer: I'm a Ramda principal team member). But these implementation show that it's fairly easy to maintain your own versions.
This really was an interesting question! Took me a while to figure it out :)
I'm not a big fan of reinventing the wheel. So I'd suggest you use a library. We like object-scan for data processing since it is very powerful once you wrap your head around it. Having said that, this question was tricky! Here is how you could solve it
// const objectScan = require('object-scan');
const data = [{ Type: 'grdparent1', name: 'grdparent1', children: [{ Type: 'grdparent1', Id: 45, children: [] }, { Type: 'grdparent1', Id: 46, children: [{ Type: 'parent1', Id: 54, children: [{ Type: 'child1', Id: 63, children: [] }, { Type: 'child2', Id: 64, children: [] }] }, { Type: 'parent2', Id: 57, children: [] }] }] }, { Type: 'grdparent2', name: 'grdparent2', children: [{ Type: 'grdparent2', Id: 4, children: [{ Type: 'parent1', Id: 16, children: [{ children: [], Type: 'child1', Id: 28 }] }, { Type: 'parent2', Id: 17, children: [] }] }] }, { Type: 'grdparent3', name: 'grdparent3', children: [] }, { Type: 'grdparent4', name: 'grdparent4', children: [{ Type: 'parent1', Id: 167, children: [] }] }];
const convert = (input) => {
objectScan(['**[*]'], {
breakFn: ({ isMatch, key, value, context }) => {
if (isMatch) {
context[key.length] = value.children.map(({ Type }) => Type);
}
},
filterFn: ({ key, value, parent, property, context }) => {
const result = 'Id' in value ? { Id: value.Id } : {};
context[key.length].forEach((type, idx) => {
result[type] = (result[type] || []).concat(value.children[idx]);
});
if (Object.keys(result).length === 0) {
parent.splice(property, 1);
} else {
parent.splice(property, 1, result);
}
}
})(input, []);
};
convert(data);
console.log(data);
// => [ { grdparent1: [ { Id: 45 }, { Id: 46, parent1: [ { Id: 54, child1: [ { Id: 63 } ], child2: [ { Id: 64 } ] } ], parent2: [ { Id: 57 } ] } ] }, { grdparent2: [ { Id: 4, parent1: [ { Id: 16, child1: [ { Id: 28 } ] } ], parent2: [ { Id: 17 } ] } ] }, { parent1: [ { Id: 167 } ] } ]
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#13.7.1"></script>
Disclaimer: I'm the author of object-scan
Note that the result matches the result of the currently accepted answer.

Categories

Resources