Get deepest level children from nested objects in javascript - javascript

I have 2 types of a objects, a group, and an item. A group can have children which is either an array of groups or an array of items.
I've ended up with a series of nested groups (which can be infinite levels deep) and I need to retrieve all the items, no matter how many levels deep, with only a group to work with.
Is there a way to retrieve all the items from the top-level group in the following data structure?
{
type: 'group',
children: [
{
type: 'group',
children: [
{
type: 'group',
children: [{type:'item'}, {type:'item'}, {type:'item'}]
},
{
type: 'group',
children: [{type:'item'}, {type:'item'}, {type:'item'}]
},
{
type: 'group',
children: [{type:'item'}, {type:'item'}, {type:'item'}]
},
]
},
{
type: 'group',
children: [
{
type: 'group',
children: [{type:'item'}]
},
{
type: 'group',
children: [{type:'item'}]
},
{
type: 'group',
children: [{type:'item'}]
},
]
},
{
type: 'group',
children: [
{
type: 'group',
children: [{type:'item'}, {type:'item'}]
},
{
type: 'group',
children: [{type:'item'}, {type:'item'}]
},
{
type: 'group',
children: [{type:'item'}, {type:'item'}]
},
]
},
]
}

You could use an iterative with Array#reduce and recursive with calling iter again, approach.
var data = { children: [{ children: [{ children: [{ name: 'item1' }, { name: 'item2' }, { name: 'item3' }] }, { children: [{ name: 'item1' }, { name: 'item2' }, { name: 'item3' }] }, { children: [{ name: 'item1' }, { name: 'item2' }, { name: 'item3' }] }] }, { children: [{ children: [{ name: 'item1' }] }, { children: [{ name: 'item1' }] }, { children: [{ name: 'item1' }] }] }, { children: [{ children: [{ name: 'item1' }, { name: 'item2' }, { name: 'item3' }] }, { children: [{ name: 'item1' }, { name: 'item2' }, { name: 'item3' }] }, { children: [{ name: 'item1' }, { name: 'item2' }, { name: 'item3' }] }] }] },
children = [data].reduce(function iter(r, a) {
if (Array.isArray(a.children)) {
return a.children.reduce(iter, r);
}
r.push(a);
return r;
}, []);
console.log(children);
.as-console-wrapper { max-height: 100% !important; top: 0; }

You can achieve it with recursion.
var data = {
children: [
{
children: [
{
children: [{ name: 'item1' }, { name: 'item2' }, { name: 'item3' }]
},
{
children: [{ name: 'item1' }, { name: 'item2' }, { name: 'item3' }]
},
{
children: [{ name: 'item1' }, { name: 'item2' }, { name: 'item3' }]
}
]
},
{
children: [
{
children: [{ name: 'item1' }]
},
{
children: [{ name: 'item1' }]
},
{
children: [{ name: 'item1' }]
}
]
},
{
children: [
{
children: [{ name: 'item1' }, { name: 'item2' }, { name: 'item3' }]
},
{
children: [{ name: 'item1' }, { name: 'item2' }, { name: 'item3' }]
},
{
children: [{ name: 'item1' }, { name: 'item2' }, { name: 'item3' }]
}
]
}
]
};
function getAllChildren(group, children) {
children = children || [];
if(group && Array.isArray(group.children)) {
group.children.forEach(function(child) {
getAllChildren(child, children)
});
}
else {
children.push(group);
}
return children;
}
console.log(getAllChildren(data));

Related

Find all children's key by specific key in a deep nested array object

const data = [
{
title: '0-0',
key: '0-0',
children: [
{
title: '0-0-0',
key: '0-0-0',
children: [
{ title: '0-0-0-0', key: '0-0-0-0' },
{ title: '0-0-0-1', key: '0-0-0-1' },
{ title: '0-0-0-2', key: '0-0-0-2' },
],
},
{
title: '0-0-1',
key: '0-0-1',
children: [
{ title: '0-0-1-0', key: '0-0-1-0' },
{ title: '0-0-1-1', key: '0-0-1-1' },
{ title: '0-0-1-2', key: '0-0-1-2' },
],
},
{
title: '0-0-2',
key: '0-0-2',
},
],
},
{
title: '0-1',
key: '0-1',
children: [
{ title: '0-1-0-0', key: '0-1-0-0' },
{ title: '0-1-0-1', key: '0-1-0-1' },
{ title: '0-1-0-2', key: '0-1-0-2' },
],
},
{
title: '0-2',
key: '0-2',
},
];
How would I get an array of all values throughout all nests of this obj by the key of id.
For example
input: ["0-0-0"]
i wanna output like this
output: ["0-0-0", "0-0-0-0", "0-0-0-1", "0-0-0-2"]
enter image description here
You can recursively loop over all the children and get the keys that either match one of the target keys or if any of their ancestors have matched one the target keys.
const data = [
{
title: "0-0",
key: "0-0",
children: [
{
title: "0-0-0",
key: "0-0-0",
children: [
{ title: "0-0-0-0", key: "0-0-0-0" },
{ title: "0-0-0-1", key: "0-0-0-1" },
{ title: "0-0-0-2", key: "0-0-0-2" },
],
},
{
title: "0-0-1",
key: "0-0-1",
children: [
{ title: "0-0-1-0", key: "0-0-1-0" },
{ title: "0-0-1-1", key: "0-0-1-1" },
{ title: "0-0-1-2", key: "0-0-1-2" },
],
},
{
title: "0-0-2",
key: "0-0-2",
},
],
},
{
title: "0-1",
key: "0-1",
children: [
{ title: "0-1-0-0", key: "0-1-0-0" },
{ title: "0-1-0-1", key: "0-1-0-1" },
{ title: "0-1-0-2", key: "0-1-0-2" },
],
},
{
title: "0-2",
key: "0-2",
},
];
function getKeys(data, targetKeys) {
const targetKeysSet = new Set(targetKeys);
const outputKeys = [];
function getKeysHelper(data, hasParentMatched = false) {
data?.forEach((d) => {
if (targetKeysSet.has(d.key) || hasParentMatched) {
outputKeys.push(d.key);
getKeysHelper(d.children, true);
} else {
getKeysHelper(d.children);
}
});
}
getKeysHelper(data);
return outputKeys;
}
getKeys(data, ["0-0-0"]);
Relevant documentations:
Optional chaining (?.)
Array.prototype.includes
Set
you can do something like this
const extractKeys = data => {
const loop = (data, res) => {
if(!data.children){
return [...res, data.key]
}
return data.children.flatMap(d => loop(d, [...res, data.key]))
}
return [...new Set(loop(data, []))]
}
const findKeys = (data, keys) => data.flatMap(extractKeys).filter(k => keys.some(key => k.includes(key)))
const data = [
{
title: '0-0',
key: '0-0',
children: [
{
title: '0-0-0',
key: '0-0-0',
children: [
{ title: '0-0-0-0', key: '0-0-0-0' },
{ title: '0-0-0-1', key: '0-0-0-1' },
{ title: '0-0-0-2', key: '0-0-0-2' },
],
},
{
title: '0-0-1',
key: '0-0-1',
children: [
{ title: '0-0-1-0', key: '0-0-1-0' },
{ title: '0-0-1-1', key: '0-0-1-1' },
{ title: '0-0-1-2', key: '0-0-1-2' },
],
},
{
title: '0-0-2',
key: '0-0-2',
},
],
},
{
title: '0-1',
key: '0-1',
children: [
{ title: '0-1-0-0', key: '0-1-0-0' },
{ title: '0-1-0-1', key: '0-1-0-1' },
{ title: '0-1-0-2', key: '0-1-0-2' },
],
},
{
title: '0-2',
key: '0-2',
},
];
console.log(findKeys(data, ['0-0-0']))

JavaScript - transform object, consolidate

I'm trying to transform the object below. I need to create a new array of unique locations, with the location and item objects in each node.
With the help of JackOfAshes I was able to get halfway there in this PEN
Transform this:
const orig = [
{
item: {
name: "cat",
id: "ca_123"
},
location: {
name: "porch",
id: "por_123"
}
},
{
item: {
name: "dog",
id: "do_123"
},
location: {
name: "porch",
id: "por_123"
}
},
{
item: {
name: "snake",
id: "sn_123"
},
location: {
name: "forest",
id: "for_123"
}
},
{
item: {
name: "bird",
id: "bi_123"
},
location: {
name: "forest",
id: "for_123"
}
},
{
item: {
name: "beer",
id: "be_123"
},
location: {
name: "fridge",
id: "fri_123"
}
}
];
Into this:
const desired = [
{
name: "porch",
id: "por_123",
items: [
{
name: "cat",
id: "ca_123"
},
{
name: "dog",
id: "do_123"
}
]
},
{
name: "forest",
id: "for_123",
items: [
{
name: "snake",
id: "sn_123"
},
{
name: "bird",
id: "bi_123"
}
]
},
{
name: "fridge",
id: "fri_123",
items: [
{
name: "beer",
id: "be_123"
}
]
}
];
You can do it, or use reduce
const orig = [
{
item: {
name: "cat",
id: "ca_123"
},
location: {
name: "porch",
id: "por_123"
}
},
{
item: {
name: "dog",
id: "do_123"
},
location: {
name: "porch",
id: "por_123"
}
},
{
item: {
name: "snake",
id: "sn_123"
},
location: {
name: "forest",
id: "for_123"
}
},
{
item: {
name: "bird",
id: "bi_123"
},
location: {
name: "forest",
id: "for_123"
}
},
{
item: {
name: "beer",
id: "be_123"
},
location: {
name: "fridge",
id: "fri_123"
}
}
];
let formattedData = {}
orig.forEach(data=>{
if(!formattedData[data.location.id]) formattedData[data.location.id]= {
id: data.location.id,
name: data.location.name,
items:[]
}
formattedData[data.location.id].items.push(data.item)
})
const finalResponse = Object.entries(formattedData).map((e) => ( { ...e[1] } ));
console.log(finalResponse)

Remove items from nested array of objects based on a condition

In my application, I have data returned from the server like below. It has very deep nesting:
var data = [{
name: "root",
children: [{
name: "Parent1",
children: [{
name: "Parent1-child1",
children: [{
name: "Parent1-child1-grandchild1",
children: [{
name: "Parent1-child1-grandchild1-last",
children:[]
}]
},
{
name: "Parent1-child1-grandchild2",
children: []
},
{
name: "Parent1-child1-grandchild3",
children: []
}
]
},
{
name: "Paren1-child2",
children: [{
name: "Parent1-chil2-grandchild1",
children: []
},
{
name: "Parent1-child2-grandchild2",
children: [{
name: "Parent1-child2-grandchild2-last",
children: []
}]
},
{
name: "Parent1-child2-grandchild3",
children: []
}
]
},
{
name: "Parent1-child3",
children: []
}
]
},
{
name: "Parent2",
children: [{
name: "Parent2-child1",
children: []
},
{
name: "Parent2-child2",
children: [{
name: "Parent2-child2-grandchild1",
children: []
},
{
name: "Parent2-child2-grandchild2",
children: [{
name: "Parent2-child2-grandchild2-last",
children: []
}]
}
]
}
]
},
{
name: "Parent3",
children: []
}
]
}];
The requirement is to loop through all the objects (deep nested level also) and remove the object if the children property has a value of an empty array. So the output should be like below
var data = [{
name: "root",
children: [{
name: "Parent1",
children: [{
name: "Parent1-child1",
children: [{
name: "Parent1-child1-grandchild1",
children: []
},
]
},
{
name: "Paren1-child2",
children: [
{
name: "Parent1-child2-grandchild2",
children: []
},
]
},
]
},
{
name: "Parent2",
children: [
{
name: "Parent2-child2",
children: [
{
name: "Parent2-child2-grandchild2",
children: []
}
]
}
]
}
]
}];
I have tried the following code, but it doesn't work as expected. Please let me know how to achieve the expected result.
function checkChildrens(arr) {
arr.forEach((ele,i) => {
if(ele.hasOwnProperty('children')) {
checkChildrens(ele['children'])
} else {
arr.splice(i,1)
}
})
}
checkChildrens(data);
I have tried with the filter method also in that case. It is not working correctly.
arr.filter((ele,i)=>{
if(ele.hasOwnProperty('children') && ele.children.length !== 0 ){
removeEmpty(ele.children)
}else{
return false;
}
return true;
})
You could rebuild new objects by checking the children array length.
function filter(array) {
return array.reduce((r, o) => {
if (o.children && o.children.length) {
r.push(Object.assign({}, o, { children: filter(o.children) }));
}
return r;
}, []);
}
var data = [{ name: "root", children: [{ name: "Parent1", children: [{ name: "Parent1-child1", children: [{ name: "Parent1-child1-grandchild1", children: [{ name: "Parent1-child1-grandchild1-last", children: [] }] }, { name: "Parent1-child1-grandchild2", children: [] }, { name: "Parent1-child1-grandchild3", children: [] }] }, { name: "Paren1-child2", children: [{ name: "Parent1-chil2-grandchild1", children: [] }, { name: "Parent1-child2-grandchild2", children: [{ name: "Parent1-child2-grandchild2-last", children: [] }] }, { name: "Parent1-child2-grandchild3", children: [] }] }, { name: "Parent1-child3", children: [] }] }, { name: "Parent2", children: [{ name: "Parent2-child1", children: [] }, { name: "Parent2-child2", children: [{ name: "Parent2-child2-grandchild1", children: [] }, { name: "Parent2-child2-grandchild2", children: [{ name: "Parent2-child2-grandchild2-last", children: [] }] }] }] }, { name: "Parent3", children: [] }] }],
result = filter(data);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Approach for removing all nested empty children (except the last one. This has an empty object, but no children property).
function filter(array) {
return array.reduce((r, o) => {
if (o.children) {
var children = filter(o.children);
if (children.length) r.push(Object.assign({}, o, { children }));
} else {
r.push(o);
}
return r;
}, []);
}
var data = [{ name: "root", children: [{ name: "Parent1", children: [{ name: "Parent1-child1", children: [{ name: "Parent1-child1-grandchild1", children: [{ name: "Parent1-child1-grandchild1-last", children: [] }] }, { name: "Parent1-child1-grandchild2", children: [] }, { name: "Parent1-child1-grandchild3", children: [] }] }, { name: "Paren1-child2", children: [{ name: "Parent1-chil2-grandchild1", children: [] }, { name: "Parent1-child2-grandchild2", children: [{ name: "Parent1-child2-grandchild2-last", children: [] }] }, { name: "Parent1-child2-grandchild3", children: [] }] }, { name: "Parent1-child3", children: [] }] }, { name: "Parent2", children: [{ name: "Parent2-child1", children: [] }, { name: "Parent2-child2", children: [{ name: "Parent2-child2-grandchild1", children: [] }, { name: "Parent2-child2-grandchild2", children: [{ name: "Parent2-child2-grandchild2-last", children: [] }] }] }] }, { name: "Parent3", children: [{}] }] }],
result = filter(data);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
var data = [{
name: "root",
children: [{
name: "Parent1",
children: [{
name: "Parent1-child1",
children: [{
name: "Parent1-child1-grandchild1",
children: [{
name: "Parent1-child1-grandchild1-last",
children: []
}]
},
{
name: "Parent1-child1-grandchild2",
children: []
},
{
name: "Parent1-child1-grandchild3",
children: []
}
]
},
{
name: "Paren1-child2",
children: [{
name: "Parent1-chil2-grandchild1",
children: []
},
{
name: "Parent1-child2-grandchild2",
children: [{
name: "Parent1-child2-grandchild2-last",
children: []
}]
},
{
name: "Parent1-child2-grandchild3",
children: []
}
]
},
{
name: "Parent1-child3",
children: []
}
]
},
{
name: "Parent2",
children: [{
name: "Parent2-child1",
children: []
},
{
name: "Parent2-child2",
children: [{
name: "Parent2-child2-grandchild1",
children: []
},
{
name: "Parent2-child2-grandchild2",
children: [{
name: "Parent2-child2-grandchild2-last",
children: []
}]
}
]
}
]
},
{
name: "Parent3",
children: []
}
]
}];
function checkChildrens(arr) {
let res = []
arr.forEach(v => {
if (v.children && v.children.length) {
res = res.concat({
name: v.name,
children: checkChildrens(v.children)
})
}
})
return res
}
console.log(checkChildrens(data));

how to filter nested array like this?

I am having response like below
let m = [
{
name: 'Summary',
subListExpanded: false,
subList: [
]
},
{
name: 'Upload',
subListExpanded: false,
subList: [
]
},
{
name: 'Tasks',
subListExpanded: false,
subList: [
]
},
{
name: 'Dashboard',
subListExpanded: false,
subList: [
]
},
{
name: 'Master',
subListExpanded: false,
subList: [
{
id: 'user-master',
name: 'User-Master'
},
{
id: 'menu-master',
name: 'Menu-Master'
},
{
id: 'entity-master',
name: 'Entity-Master'
},
{
id: 'vendor-master',
name: 'Vendor-Master'
},
{
id: 'xxx-master',
name: 'xxx-Master'
}
]
}
];
If i search m the filter should be like this
[
{
name: 'Summary',
subListExpanded: false,
subList: [
]
},
{
name: 'Master',
subListExpanded: false,
subList: [
{
id: 'user-master',
name: 'User-Master'
},
{
id: 'menu-master',
name: 'Menu-Master'
},
{
id: 'entity-master',
name: 'Entity-Master'
},
{
id: 'vendor-master',
name: 'Vendor-Master'
},
{
id: 'xxx-master',
name: 'xxx-Master'
}
]
}
];
if i search master the filter response should like this?
[
{
name: 'Master',
subListExpanded: false,
subList: [
{
id: 'user-master',
name: 'User-Master'
},
{
id: 'menu-master',
name: 'Menu-Master'
},
{
id: 'entity-master',
name: 'Entity-Master'
},
{
id: 'vendor-master',
name: 'Vendor-Master'
},
{
id: 'xxx-master',
name: 'xxx-Master'
}
]
}
];
if i search xxx-master the filter response should be
[
{
name: 'Master',
subListExpanded: false,
subList: [
{
id: 'xxx-master',
name: 'xxx-Master'
}
]
}
];
if i search slkvcsmcskc filter response like
[]
my typescript code is not working properly .please help me to fix this>
m.filter(x=> x.name.toLowerCase() === search.toLowerCase() || x.subList.some(x1=> x1.name.toLowerCase()===search.toLowerCase()))
The following code gives the desired output. Note that I added some complexity which may not be needed for your use case. However, the example should work for lists with arbitrary deep nesting (see 'bar' example).
let m = [
{
name: 'Summary',
subListExpanded: false,
subList: [
]
},
{
name: 'Upload',
subListExpanded: false,
subList: [
{
name: 'foo',
subList: [
{
name: 'bar',
}
],
}
]
},
{
name: 'Tasks',
subListExpanded: false,
subList: [
]
},
{
name: 'Dashboard',
subListExpanded: false,
subList: [
]
},
{
name: 'Master',
subListExpanded: false,
subList: [
{
id: 'user-master',
name: 'User-Master'
},
{
id: 'menu-master',
name: 'Menu-Master'
},
{
id: 'entity-master',
name: 'Entity-Master'
},
{
id: 'vendor-master',
name: 'Vendor-Master'
},
{
id: 'xxx-master',
name: 'xxx-Master'
}
]
}
];
function search (input, query) {
const queryReg = new RegExp(query, 'i');
function searchInternal (data) {
let result = [];
data.forEach(item => {
const parentMatch = queryReg.test(item.name);
let subMatch = false;
if (item.subList) {
let subResult = searchInternal(item.subList);
subMatch = subResult.length > 0;
item.subList = subMatch ? subResult : [];
}
// push parent if it matches for itself or a child (list) matches
if (parentMatch || subMatch) result.push(item);
});
return result;
}
return searchInternal(JSON.parse(JSON.stringify(input)) /* create a working copy with JSON.parse(...) */);
}
console.log('master', search(m, 'master'));
console.log('xxx-master', search(m, 'xxx-master'));
console.log('m', search(m, 'm'));
console.log('bar', search(m, 'bar'));
console.log('slkvcsmcskc', search(m, 'slkvcsmcskc'));
Actually it should go like this:
obj = {
_id: "sjkd9skj",
data: {
dektop: [
{
x: 2,
y: 3,
t: { key: 'aabbcc'}
},
...
],
mobile: [
{
x: 4,
y: 3,
t: { key: 'ffff'}
},
...
],
print: [
{
x: 7,
y: 5,
t: { key: 'ppp'}
},
...
]
}
}

Find node by id in json tree

I want to add the children array to node where id = 52126f7d (or another). How do I do it?
var children = [
{ name: 'great-granchild3',
id: '2a12a10h'
},
{ name: 'great-granchild4',
id: 'bpme7qw0'
}
]
// json tree
var objects = {
name: 'all objects',
id:"2e6ca1c3",
children: [
{
name: 'child',
id: "6c03cfbe",
children: [
{ name: 'grandchild1',
id: "2790f59c"
},
{ name: 'grandchild2',
id: "52126f7d"
},
{ name: 'grandchild3',
id: "b402f14b"
},
{
name: 'grandchild4',
id: "6c03cff0",
children: [
{ name: 'great-grandchild1',
id: "ce90ffa6"
},
{ name: 'great-grandchild2',
id: "52f95f28"
}
]
}
]
},
{
name: 'child2',
id: "7693b310",
children: [
{ name: 'grandchild5',
id: "def86ecc"
},
{ name: 'grandchild6',
id: "6224a8f8"
}
]
}
]
}
to end up with
var objects = {
name: 'all objects',
id:"2e6ca1c3",
children: [
{
name: 'child',
id: "6c03cfbe",
children: [
{ name: 'grandchild1',
id: "2790f59c"
},
{ name: 'grandchild2',
id: "52126f7d",
children = [
{ name: 'great-granchild3',
id: '2a12a10h'
},
{ name: 'great-granchild4',
id: 'bpme7qw0'
}
]
},
{ name: 'grandchild3',
id: "b402f14b"
},
{
name: 'grandchild4',
id: "6c03cff0",
children: [
{ name: 'great-grandchild1',
id: "ce90ffa6"
},
{ name: 'great-grandchild2',
id: "52f95f28"
}
]
}
]
},
{
name: 'child2',
id: "7693b310",
children: [
{ name: 'grandchild5',
id: "def86ecc"
},
{ name: 'grandchild6',
id: "6224a8f8"
}
]
}
]
}
by finding the proper node first.
function getNodeById(id, node){
var reduce = [].reduce;
function runner(result, node){
if(result || !node) return result;
return node.id === id && node || //is this the proper node?
runner(null, node.children) || //process this nodes children
reduce.call(Object(node), runner, result); //maybe this is some ArrayLike Structure
}
return runner(null, node);
}
var target = getNodeById("52126f7d", objects);
target.children = children;
How about:
objects.children[0].children[1].children = children;

Categories