Build list of ancestors from nested array - javascript

The nested array looks like this:
var arr = [{
id: 2,
name: 'a',
children: []
}, {
id: 5,
name: 'b',
children: [{
id: 14,
name: 'b2'
}]
}, {
id: 15,
name: 'd',
children: []
}];
How can I make a list of ancestor elements, from any given element?
For example, if given element has id: 14 the list should return only the parent:
[{
id: 5,
name: 'b',
children: [...]
}]
I'm looking to replicate a "breadcrumb" navigation

You could handover an object which is the parent and search recursive for the wanted id.
function getParent(object, id) {
var result;
(object.children || []).some(o => result = o.id === id ? object : getParent(o, id));
return result;
}
var array = [{ id: 2, name: 'a', children: [] }, { id: 5, name: 'b', children: [{ id: 14, name: 'b2' }] }, { id: 15, name: 'd', children: [] }];
console.log(getParent({ children: array }, 14));
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you like to hand over the array, you could take a nested approach with recursive function.
function getParent(children, id) {
function iter(object) {
var result;
(object.children || []).some(o => result = o.id === id ? object : iter(o));
return result;
}
return iter({ children });
}
var array = [{ id: 2, name: 'a', children: [] }, { id: 5, name: 'b', children: [{ id: 14, name: 'b2' }] }, { id: 15, name: 'd', children: [] }];
console.log(getParent(array, 14));
.as-console-wrapper { max-height: 100% !important; top: 0; }

If we can assume that only two levels exist (parents and children, not children of children) then the following function findAncestor() does what you need. It iterates over all parent elements and checks if they have a child with the relevant ID.
function findAncestor(id) {
for (let i = 0; i < arr.length; i++) {
let obj = arr[i];
if (obj.hasOwnProperty('children')) {
if (obj.children.length > 0) {
for (let j = 0; j < obj.children.length; j++) {
if (obj.children[j].id === id) {
return obj;
}
}
}
}
}
return null;
}
console.info(findAncestor(14));
If you need to handle the case that a child with same ID can occur in several parents, you should use a result array and add all found results to it before returning it in the end.

You can try this way,
var arr = [{
id: 2,
name: 'a',
children: []
}, {
id: 5,
name: 'b',
children: [{
id: 14,
name: 'b2'
}]
}, {
id: 15,
name: 'd',
children: []
}];
function getAncestor(obj,id,ancestor){
if(obj.id===id){
console.log(ancestor);
}
else
if(obj&& obj.children && obj.children.length)
obj.children.forEach(item=>this.getAncestor(item,id,obj));
}
arr.forEach(o=>getAncestor(o,14,{}));

The Depth First Search Algorithm - get parent node is:
function getParentNodeByKey(obj, targetId, paramKey) {
if (obj.children) {
if (obj.children.some(ch => ch[paramKey] === targetId))
return obj;
else {
for (let item of obj.children) {
let check = this.getParentNodeByKey(item, targetId, paramKey)
if (check) {
return check;
}
}
}
}
return null
}
and code to test:
var arr = [{
id: 2,
name: 'a',
children: []
}, {
id: 5,
name: 'b',
children: [{
id: 14,
name: 'b2'
}]
}, {
id: 15,
name: 'd',
children: []
}];
let parentElement;
const valueToFind = 14;
const desiredkey = 'id';
for (let i = 0; i < arr.length; i++) {
parentElement = getParentNodeByKey(arr[i], valueToFind, desiredkey);
if(parentElement)
break;
}
console.log(`The parent element is:`, parentElement);

Related

Move item anywhere in a nested array

I've managed to copy the intended object into the intended location (my code is below), but how do I move it? So it will not exist in the original location any more.
So in my example, I want to take the object with id of 14 (very bottom of the object) and move it into the children of the object with id of 3 (towards the top).
I know I need to modify this line: item.children.push(itemToMove) in my moveItem function, but some reason I can't think of it.
Also sorry about the very big/nested object, I wanted to make sure to cover a deeply nested object.
const myObj = [
{
id: 1,
name: '1',
children: [
{
id: 2,
name: '2',
children: [
{
id: 3,
name: '3',
children: []
}
]
},
{
id: 4,
name: '4',
children: [
{
id: 5,
name: '5',
children: [
{
id: 6,
name: '6',
children: [
{
id: 7,
name: '7',
children: []
}
]
}
]
}
]
},
]
},
{
id: 8,
name: '8',
children: [
{
id: 9,
name: '9',
children: [
{
id: 10,
name: '10',
children: []
}
]
},
{
id: 11,
name: '11',
children: [
{
id: 12,
name: '12',
children: [
{
id: 13,
name: '13',
children: [
{
id: 14,
name: '14',
children: []
}
]
}
]
}
]
},
]
}
]
let itemToMove = {
id: 14,
name: '14',
children: []
}
// move item, return updated obj
function moveItem(itemToMove, obj, parentId) {
for (let i=0;i<obj.length;i++) {
const value = obj[i];
const item = search(obj[i], parentId);
if (item) {
item.children.push(itemToMove); // pushed into children, but need to move not duplicate in
break;
}
}
function search(obj, id) {
if (obj.id === id) {
return obj;
}
for (let i=0;i<obj.children.length;i++) {
const possibleResult = search(obj.children[i], id);
if (possibleResult) {
return possibleResult;
}
}
}
return obj;
};
console.log(moveItem(itemToMove, myObj, 3))
I would probably do something like this, taking into account that if the insert fails, you should have some kind of way to re-instate the data. I also used ES6 which is different to your code, but it gives you some kind of idea.
let parent
function removeItem (obj, itemToFind) {
// Loop the object
obj.find((e, index) => {
// If the id's match remove from the parent if it exists otherwise from the object as its at root level
if (e.id === itemToFind.id) {
if (parent) {
parent.children.splice(index, 1)
} else {
obj.splice(index, 1)
}
// break the loop once returned true. Change find to forEach to remove all instances with id if allowing multiples
return true
}
// recurse
else if (e.children && e.children.length > 0) {
parent = e
return removeItem(e.children, itemToFind)
}
})
}
// move item, return updated obj
function moveItem (itemToMove, obj, parentId) {
for (let i = 0; i < obj.length; i++) {
const value = obj[i]
const item = search(obj[i], parentId)
if (item) {
item.children.push(itemToMove) // pushed into children, but need to move not duplicate in
break
}
}
function search (obj, id) {
if (obj.id === id) {
return obj
}
for (let i = 0; i < obj.children.length; i++) {
const possibleResult = search(obj.children[i], id)
if (possibleResult) {
return possibleResult
}
}
}
return obj
};
removeItem(myObj, itemToMove)
moveItem(itemToMove, myObj, 3)

Recursively get all children

I need to recursively get all children from a nested object.
I already wrote a function that does it (kinda) but I think it can be improved.
How can I make it shorter and cleaner?
I have included the data I'm using for testing as well as the function I wrote that needs improvement.
let data = [{
id: 1,
child: {
id: 2,
child: {
id: 3,
child: {
id: 4,
child: null
}
}
}
},
{
id: 5,
child: {
id: 6,
child: null
}
}
];
// function
for (let cat of data) {
cat.children = getCategoryChild(cat);
console.log(cat.children)
}
function getCategoryChild(cat) {
let t = [];
if (cat.child != null) {
t.push(cat.child);
let y = getCategoryChild(cat.child);
if (y.length > 0) {
for (let i of y) {
t.push(i)
}
}
}
return t;
}
Expected output:
[{id: 1, children: [{id: 2}, {id: 3}, {id: 4}]}, {id: 5, children: [{id: 6}]}]
You could take a recursive approach by checking the actual child property
function convert(array) {
const iter = o => o ? [{ id: o.id }, ...iter(o.child)] : [];
return array.map(({ id, child }) => ({ id, children: iter(child) }));
}
var data = [{ id: 1, child: { id: 2, child: { id: 3, child: { id: 4, child: null } } } }, { id: 5, child: { id: 6, child: null } }];
console.log(convert(data));
.as-console-wrapper { max-height: 100% !important; top: 0; }
assuming that each category only ever has one child
edited to adhere to the expected result...
function iterChildren(cat) {
let c = cat, children = [];
while (c.child) {
children.push({id: c.child.id});
c = c.child;
}
return {id: cat.id, children: children};
}
let newData = data.map(iterChildren);
I re-wrote the function.
It filters cats, and only returns an object with id and child_id of each.
let output = [],
data = [{
id: 1,
child: {
id: 2,
child: {
id: 3,
child: {
id: 4,
child: null
}
}
}
},
{
id: 5,
child: {
id: 6,
child: null
}
}
];
function getCategoryChild(cat) {
var t = [{
id: cat.id,
child_id: null
/* HERE you can set, what kind of data should be included to output */
}]
if (cat.child) {
t[0].child_id = cat.child.id
t = t.concat(getCategoryChild(cat.child))
}
return t
}
for (x of data) {
output=output.concat(getCategoryChild(x))
}
console.log(output)
EDIT: I edited my code assuming that one cat can have more children:
let output = [],
data = [{
id: 1,
child: {
id: 2,
child: {
id: 3,
child: {
id: 4,
child: null
}
}
}
},
{
id: 5,
child: {
id: 6,
child: null
}
},
{
id: 7,
child: [
{
id: 8,
child: {
id: 9,
child: null
}
},
{
id: 10,
child: null
},
{
id: 11,
child: null
}
]
},
];
function getCategoryChild(cat) {
var t = [{
id: cat.id,
child_id: []
/* HERE you can set, what kind of data should be included to output */
}]
if (cat.child) {
if (!(cat.child instanceof Array)) {
cat.child = [cat.child]
}
for (var x of cat.child) {
t[0].child_id.push(x.id)
t = t.concat(getCategoryChild(x))
}
}
return t
}
for (x of data) {
output = output.concat(getCategoryChild(x))
}
console.log(output)
data.map(({id,child:c})=>({id,children:[...{*0(){for(;c&&({id}=c);c=c.child)yield{id}}}[0]()]}))

deleting an element in nested array using filter() function

I have been trying to delete an element with an ID in nested array.
I am not sure how to use filter() with nested arrays.
I want to delete the {id: 111,name: "A"} object only.
Here is my code:
var array = [{
id: 1,
list: [{
id: 123,
name: "Dartanan"
}, {
id: 456,
name: "Athos"
}, {
id: 789,
name: "Porthos"
}]
}, {
id: 2,
list: [{
id: 111,
name: "A"
}, {
id: 222,
name: "B"
}]
}]
var temp = array
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array[i].list.length; j++) {
temp = temp.filter(function(item) {
return item.list[j].id !== 123
})
}
}
array = temp
You can use the function forEach and execute the function filter for every array list.
var array = [{ id: 1, list: [{ id: 123, name: "Dartanan" }, { id: 456, name: "Athos" }, { id: 789, name: "Porthos" }] }, { id: 2, list: [{ id: 111, name: "A" }, { id: 222, name: "B" }] }];
array.forEach(o => (o.list = o.list.filter(l => l.id != 111)));
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
To remain the data immutable, use the function map:
var array = [{ id: 1, list: [{ id: 123, name: "Dartanan" }, { id: 456, name: "Athos" }, { id: 789, name: "Porthos" }] }, { id: 2, list: [{ id: 111, name: "A" }, { id: 222, name: "B" }] }],
result = array.map(o => ({...o, list: o.list.filter(l => l.id != 111)}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You could create a new array which contains elements with filtered list property.
const result = array.map(element => (
{
...element,
list: element.list.filter(l => l.id !== 111)
}
));
You can use Object.assign if the runtime you are running this code on does not support spread operator.
Array.filter acts on elements:
var myArray = [{something: 1, list: [1,2,3]}, {something: 2, list: [3,4,5]}]
var filtered = myArray.filter(function(element) {
return element.something === 1;
// true = keep element, false = discard it
})
console.log(filtered); // logs [{something: 1, list: [1,2,3]}]
You can use it like this:
var array = [{
id: 1,
list: [{
id: 123,
name: "Dartanan"
}, {
id: 456,
name: "Athos"
}, {
id: 789,
name: "Porthos"
}]
}, {
id: 2,
list: [{
id: 111,
name: "A"
}, {
id: 222,
name: "B"
}]
}]
for (var i = 0; i < array.length; ++i) {
var element = array[i]
// Filter the list
element.list = element.list.filter(function(listItem) {
return listItem.id !== 111 && listItem.name !== 'A';
})
}
console.log(array)

how to flat array js

How to flatten this array :
[
{ID: 0 , TITLE: 'A', children: [{ID: 1, TITLE: 'AA'}]},
{ID: 2 , TITLE: 'B', children: []},
{ID: 3 , TITLE: 'C', children: [{ID: 4, TITLE: 'CC', children:[{ID: 5, TITLE: 'CCC'}]}]}
]
To get something like this :
A
A / AA
B
C / CC / CCC
You could use store the nested item of the actual object and take an iterative and recursive approach with a closure over the path.
For an incrementing ID, you could use either an additional variable for incrementing if a new row is found or iterate at the end the given array and add the index as id.
This proposal uses an additional id variable, because it requires no extra loop.
var array = [{ ID: 0, TITLE: 'A', children: [{ ID: 1, TITLE: 'AA' }] }, { ID: 2, TITLE: 'B', children: [] }, { ID: 3, TITLE: 'C', children: [{ ID: 4, TITLE: 'CC', children: [{ ID: 5, TITLE: 'CCC' }] }] }],
id = 0,
result = array.reduce(function f(p) {
return function (r, o) {
var temp = p.concat(o.TITLE);
r.push({ ID: id++, TITLE: temp.join('/') });
if (o.children) {
o.children.reduce(f(temp), r);
}
return r;
};
}([]), []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
There's no need to complicate things here, you just need a function that loop over the array items, get their TITLE and if the item has children, we call the function recursively:
function getLevels(array, parent) {
var results = [];
array.forEach(function(el) {
results.push(!parent ? el["TITLE"] : parent + "/" + el["TITLE"]);
let prefix = parent ? parent + "/" + el["TITLE"] : el["TITLE"];
if (el.children && el.children.length > 0) {
getLevels(el.children, prefix).forEach(function(child) {
results.push(child);
});
}
});
return results;
}
Demo:
var arr = [{
ID: 0,
TITLE: 'A',
children: [{
ID: 1,
TITLE: 'AA'
}]
},
{
ID: 2,
TITLE: 'B',
children: []
},
{
ID: 3,
TITLE: 'C',
children: [{
ID: 4,
TITLE: 'CC',
children: [{
ID: 5,
TITLE: 'CCC'
}]
}]
}
];
function getLevels(array, parent) {
var results = [];
array.forEach(function(el) {
results.push(!parent ? el["TITLE"] : parent + "/" + el["TITLE"]);
let prefix = parent ? parent + "/" + el["TITLE"] : el["TITLE"];
if (el.children && el.children.length > 0) {
getLevels(el.children, prefix).forEach(function(child) {
results.push(child);
});
}
});
return results;
}
console.log(getLevels(arr));
Edit:
This is how to proceed to get the id in the array:
results.push({
"ID": el["ID"],
"TITLE": (!parent ? el["TITLE"] : parent + "/" + el["TITLE"])
});
Demo:
var arr = [{
ID: 0,
TITLE: 'A',
children: [{
ID: 1,
TITLE: 'AA'
}]
},
{
ID: 2,
TITLE: 'B',
children: []
},
{
ID: 3,
TITLE: 'C',
children: [{
ID: 4,
TITLE: 'CC',
children: [{
ID: 5,
TITLE: 'CCC'
}]
}]
}
];
function getLevels(array, parent) {
var results = [];
array.forEach(function(el) {
results.push({
"ID": el["ID"],
"TITLE": (!parent ? el["TITLE"] : parent + "/" + el["TITLE"])
});
let prefix = parent ? parent + "/" + el["TITLE"] : el["TITLE"];
if (el.children && el.children.length > 0) {
getLevels(el.children, prefix).forEach(function(child) {
results.push(child);
});
}
});
return results;
}
console.log(getLevels(arr));
Did you want something like this?
function merge(input, flat_array) {
if (!flat_array) {
// this is the initial recursive call, make the input
// (an array) have the same { child:[] } structure
// as children calls will end up having
flat_array = [];
input = { children: input };
} else {
// since the parent call is just a plain array it doesnt
// have a title so dont bother inserting anything
flat_array.push(input.TITLE);
}
for (let i in input.children) {
// recursively merge the children in into the flat array
// too
merge(input.children[i], flat_array);
}
return flat_array;
}
merge(x);
produces:
["A", "AA", "B", "C", "CC", "CCC"]

Javascript - Nested parent/child array recursive function that flattens parent only

I have a multidimensional nested parent/child array as follows:
{
parent: {
name: "foo"
},
children: [
{
parent: {
name: "asdf",
},
children: []
},
{
parent: {},
children: []
},
{
parent: {},
children: []
},
...
]
}
What I want to do is apply a recursive function on this array, to flatten only the parent property and keep children as-is, in order to get something like this:
{
name: "foo",
children: [
{
name: "asdf",
children: []
},
{
children: []
},
{
children: []
},
...
]
}
I tried using underscore.js but I am unable to find a recursive function that could do the trick. Any thoughts?
You could use an iterative and recursive approach by iterating the array and updating the wanted properties.
If a children is found, iterate again.
var array = [{ parent: { name: 'a', surname: 'b', }, children: [{ parent: { name: 'c', surname: 'd', }, children: [{ parent: { name: 'e', surname: 'f' } }], childrenName: 'v', childrenSurname: 'w' }], childrenName: 'x', childrenSurname: 'y' }];
array.forEach(function iter(object) {
if (object.parent) {
object.name = object.parent.name;
object.surname = object.parent.surname;
delete object.parent;
}
object.children && object.children.forEach(iter);
});
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
hope this recurse function is what you need
const recurse = (data) => {
for(let i = 0, l = data.length; i < l; i++){
if(data[i]['parent']){
data[i]['name'] = data[i]['parent']['name']
delete data[i]['parent']
}
if(data[i]['children']) recurse(data[i]['children'])
}
}

Categories

Resources