Iterate through each object array based on condition check - javascript

I have a scenario were I need to iterate through each parent/child array in an object.
Each Grandparents can have multiple parents, in same fashion each parent can have multiple childs, each child can have multiple subChilds and so on.
I need to check if type is "parent" or "child" while iterating and then push name property to an array as mentioned in expected output.
Input Object:
var inputObject = {
"id": 1,
"name": "Grand Parent 1",
"type": "GrandParent",
"childType": [
{
"id": 2,
"type": "Parent",
"childType": [
{
"id": 3,
"type": "Child",
"childType": [],
"name": "Child 11"
},
{
"id": 4,
"type": "Child",
"childType": [],
"name": "Child 12"
}
],
"name": "Parent 1"
},
{
"id": 5,
"type": "Parent",
"childType": [
{
"id": 6,
"type": "Child",
"childType": [],
"name": "Child 21"
}
],
"name": "Parent 2"
},
{
"id": 7,
"type": "Parent",
"childType": [
{
"id": 8,
"type": "Child",
"childType": [],
"name": "Child 31"
}
],
"name": "Parent 3"
}
]
}
Code Tried:
function handleData({childType, ...rest}){
const res = [];
res.push(rest.name);
if(childType){
if(rest.type == "Child")
res.push(...handleData(childType));
}
return res;
}
const res = handleData(inputObject);
Expected Output:
If type selected is "Parent"
["Parent 1", "Parent 2, Parent 3"]
if type selected is "Child"
["Child 11", "Child 12", "Child 21", "Child 31"]

You can do a recursive function that uses flatMap():
const obj = {id:1,name:"Grand Parent 1",type:"GrandParent",childType:[{id:2,type:"Parent",childType:[{id:3,type:"Child",childType:[],name:"Child 11"},{id:4,type:"Child",childType:[],name:"Child 12"}],name:"Parent 1"},{id:5,type:"Parent",childType:[{id:6,type:"Child",childType:[],name:"Child 21"}],name:"Parent 2"},{id:7,type:"Parent",childType:[{id:8,type:"Child",childType:[],name:"Child 31"}],name:"Parent 3"}]};
const get = (o, t) => o.type === t ? [o.name] : o.childType.flatMap(c => get(c, t));
console.log(get(obj, 'GrandParent'));
console.log(get(obj, 'Parent'));
console.log(get(obj, 'Child'));

You can do that using recursion.
Steps:
Create a wrapper function in which you declare result array.
Inside that make a wrapper function create a function which would be called recursively
Check if type matches the given type add the name of object to result
Then check if elements exists in its childType. If yes yes then call function on each each of its element.
var inputObject = { "id": 1, "name": "Grand Parent 1", "type": "GrandParent", "childType": [ { "id": 2, "type": "Parent", "childType": [ { "id": 3, "type": "Child", "childType": [], "name": "Child 11" }, { "id": 4, "type": "Child", "childType": [], "name": "Child 12" } ], "name": "Parent 1" }, { "id": 5, "type": "Parent", "childType": [ { "id": 6, "type": "Child", "childType": [], "name": "Child 21" } ], "name": "Parent 2" }, { "id": 7, "type": "Parent", "childType": [ { "id": 8, "type": "Child", "childType": [], "name": "Child 31" } ], "name": "Parent 3" } ] }
function handleData(obj,type){
let res = [];
function recursive(obj){
if(type === obj.type) res.push(obj.name);
if(obj.childType.length){
obj.childType.forEach(a => recursive(a));
}
}
recursive(obj)
return res;
}
console.log(handleData(inputObject,"Child"))
console.log(handleData(inputObject,"Parent"))

Recursion is elegant but you could use es6 to do it , if the object childType was very large, recursion might not be applicable (stack overflow), here is a solution using reduce,
function getType({childType}, type) {
return childType.reduce( (acc, {type: objectType, name}) => {
if (objectType === type){
acc.push(name)
}
return acc
}, [])
}

You can solve this problem using recursion. You can try on this way !
var inputObject = {
"id": 1,
"name": "Grand Parent 1",
"type": "GrandParent",
"childType": [
{
"id": 2,
"type": "Parent",
"childType": [
{
"id": 3,
"type": "Child",
"childType": [],
"name": "Child 11"
},
{
"id": 4,
"type": "Child",
"childType": [],
"name": "Child 12"
}
],
"name": "Parent 1"
},
{
"id": 5,
"type": "Parent",
"childType": [
{
"id": 6,
"type": "Child",
"childType": [],
"name": "Child 21"
}
],
"name": "Parent 2"
},
{
"id": 7,
"type": "Parent",
"childType": [
{
"id": 8,
"type": "Child",
"childType": [],
"name": "Child 31"
}
],
"name": "Parent 3"
}
]
};
var resultValues = [];
function getResult(inputObject, propertyName, propertyValue) {
for (var objectProperty in inputObject) {
if (objectProperty == propertyName && inputObject[objectProperty] == propertyValue) {
resultValues.push(inputObject['name']);
console.log(resultValues);
} else {
if (objectProperty == 'childType') {
inputObject[objectProperty].forEach(function (element) {
getResult(element, propertyName, propertyValue)
});
}
}
}
//console.log(resultValues);
}
getResult(inputObject, 'type', 'GrandParent');
getResult(inputObject, 'type', 'Parent');
getResult(inputObject, 'type', 'Child');

Related

How to combine nested duplicate dictionary values within an array

I have a following data structure, array of dictionaries
[
{
"id": 1,
"name": "Some Name 1",
"topics": [
{
"id": 3,
"name": "Topic Name",
"topics": [],
},
{
"id": 3,
"name": "Topic Name",
"topics": [],
}
]
},
{
"id": 2,
"name": "Some Name 2",
"topics": [
{
"id": 3,
"name": "Topic Name",
"topics": [],
},
{
"id": 3,
"name": "Topic Name",
"topics": [],
}
]
},
[
{
"id": 1,
"name": "Some Name 2",
"topics": [
{
"id": 1,
"name": "Topic Name 1",
"topics": [],
},
{
"id": 2,
"name": "Topic Name 2",
"topics": [],
}
]
},
{
"id": 2,
"name": "Some Name 1",
"topics": [
{
"id": 3,
"name": "Topic Name",
"topics": [],
},
{
"id": 3,
"name": "Topic Name",
"topics": [],
}
]
},
I want to essentially be able to combine the arrays within each dictionary if I have the same id, so for each dictionary i will have higher level dictionary items being the same and essentially combine those together to avoid duplication. Preferably i would like it to be recursively being that in case the topics within topics are also duplicate (you can assume the order is always respected).
I would appreciate if you could share a solution to this

typescript: traverse nested array of objects until condition is met

I have nested array like following.
const tree = {
"id": 1,
"name": "mainOrgName",
"children": [
{
"id": 10,
"name": "East Region",
"children": [
{
"id": 11,
"name": "test east sub 1",
"children": [
{
"id": 12,
"name": "sub 22 sub 1",
"children": [
{
"id": 15,
"name": "sub 333 of sub ",
"children": [
{
"id": 16,
"name": "sub 4444",
"children": []
}
]
}
]
}
]
}
]
},
{
"id": 13,
"name": "west region",
"children": [
{
"id": 14,
"name": "test west sub 1",
"children": []
}
]
}
]
}
I need to traverse through tree.children array to get all id and name of sub arrays and its children until we didn't find children array empty. (Note: children array may be empty or may have further levels)
I need result like follows
Expected result
[
{
"name": "East Region",
"value": 10,
"selected": false
},
{
"name": "test east sub 1",
"value": 11,
"selected": false
},
{
"name": "sub 22 sub 1",
"value": 12,
"selected": false
},
{
"name": "sub 333 of sub",
"value": 15,
"selected": false
},
{
"name": "sub 4444",
"value": 16,
"selected": false
},
{
"name": "west region",
"value": 13,
"selected": false
},
{
"name": "test west sub 1",
"value": 14,
"selected": false
},
]
I tried following
const candidates = tree.children.map(org => ({name: org.name, value: org.id, selected: false}));
but it gives me following
[
{
"name": "East Region",
"value": 10,
"selected": false
},
{
"name": "west region",
"value": 13,
"selected": false
}
]
I am trying to get that but not sure how I can put condition that traverse until children is empty and push required fields in final array in required format. May need recursive/call back functions but not sure how I can use that.
Please help to get expected result. Thanks
Try this,
const tree = {
"id": 1,
"name": "mainOrgName",
"children": [
{
"id": 10,
"name": "East Region",
"children": [{
"id": 11,
"name": "test east sub 1",
"children": [{
"id": 12,
"name": "sub 22 sub 1",
"children": [{
"id": 15,
"name": "sub 333 of sub ",
"children": [{
"id": 16,
"name": "sub 4444",
"children": []
}]
}]
}]
}]
},
{
"id": 13,
"name": "west region",
"children": [{
"id": 14,
"name": "test west sub 1",
"children": []
}]
}
]
}
let items = []
let result = lootIt(tree.children)
console.log(result)
function lootIt (arr) {
for(let i = 0 ; i< arr.length ; i++){
let obj = {}
obj['name'] = arr[i]['name']
obj['value'] = arr[i]['id']
obj['selected'] = false
items.push(obj)
if(arr[i].children !== 0){
lootIt(arr[i].children)
}
}
return items
}
You can use recursion to do it
const tree = {
"id": 1,
"name": "mainOrgName",
"children": [
{
"id": 10,
"name": "East Region",
"children": [
{
"id": 11,
"name": "test east sub 1",
"children": [
{
"id": 12,
"name": "sub 22 sub 1",
"children": [
{
"id": 15,
"name": "sub 333 of sub ",
"children": [
{
"id": 16,
"name": "sub 4444",
"children": []
}
]
}
]
}
]
}
]
},
{
"id": 13,
"name": "west region",
"children": [
{
"id": 14,
"name": "test west sub 1",
"children": []
}
]
}
]
}
function mapTree(children){
let result =[]
for(c of children){
result.push({name: c.name, value: c.id, selected: false})
result = result.concat(mapTree(c.children))
}
return result
}
console.log(mapTree(tree.children))

Combine pockets of two multidimensional arrays in JavaScript

I have two arrays that have a structure given below.
I need to combine the values of two arrays into one and the order should be in sequence. I need to keep the other pockets too.
The header should be first then the child and then the next header then the next child's pockets.
const header = {
"list": [{
"name": "header-a",
"id": "id-a"
}, {
"name": "header-b",
"id": "id-b"
}]
};
const child = {
"list": [{
"name": "child",
"id": "c1",
'type': "id-a"
},
{
"name": "child 2",
"id": "c2",
'type': "id-a"
},
{
"name": "child 4",
"id": "c4",
'type': "id-b"
},
{
"name": "child-5",
"id": "c5",
'type': "id-b"
}]
};
expected result is
const result = {
"list": [{
"name": "header-a",
"header": true,
},
{
"name": "child",
"id": "c1",
'type': "id-a"
},
{
"name": "child 2",
"id": "c2",
'type': "id-a"
},
{
"name": "header-b",
"header": true,
},
{
"name": "child 4",
"id": "c4",
'type': "id-b"
},
{
"name": "child-5",
"id": "c5",
'type': "id-b"
}]
};
You loop through the headers and for each header, you push into the "combined" array an item like { name: header.name, header: true }, then filter all children whose type is equal to the header id and push them too into the array:
const header = {
"list": [{
"name": "header-a",
"id": "id-a"
}, {
"name": "header-b",
"id": "id-b"
}]
};
const child = {
"list": [{
"name": "child",
"id": "c1",
'type': "id-a"
},
{
"name": "child 2",
"id": "c2",
'type': "id-a"
},
{
"name": "child 4",
"id": "c4",
'type': "id-b"
},
{
"name": "child-5",
"id": "c5",
'type': "id-b"
}
]
};
const combined = { list: [] };
header.list.forEach(h => {
combined.list.push({ name: h.name, header: true });
child.list.filter(c => c.type === h.id).forEach(c => combined.list.push(c));
});
console.log(combined);

Get nearest parent object in nested array

I have the following array:
const items = [
{
"id": 1,
"name": "Menu 1",
"content": [
{
"id": 2,
"name": "Submenu 1 OF 1",
"url": "teste"
}
]
},
{
"id": 3,
"name": "Menu 2",
"content": [
{
"id": 4,
"name": "Submenu 1 OF 2",
"url": "teste"
},
{
"id": 5,
"name": "Submenu 2 OF 2",
"content": [
{
"id": 6,
"name": "Sub submenu 1 OF 2",
"url": "teste"
},
{
"id": 7,
"name": "Sub submenu 2 OF 2",
"url": "teste"
},
]
}
]
}
]
I need a function that given the id gets the closest parent object. For example, if I give the id 2 it returns {"id: 1, "name": "Menu 1", "content": [...]}. If I give the id 6 it returns {"id": 5, "name": "Submenu 2 OF 2", content: [...]}.
I have tried but i can only get the top-level parent and not the closest one.
EDIT: the code that i have tested so far:
let findDeep = function(data, id) {
return data.find(function(e) {
if(e.id == id) return e;
else if(e.content) return findDeep(e.content, id);
}
})
You can use a recursive depth-first search:
function findParent(items, id, parent=null) {
for (let item of items) {
let res = item.id === id ? parent
: item.content && findParent(item.content, id, item);
if (res) return res;
}
}
// demo: find parent of id=6 in example tree:
const items = [{"id": 1,"name": "Menu 1","content": [{"id": 2,"name": "Submenu 1 OF 1","url": "teste"}]},{"id": 3,"name": "Menu 2","content": [{"id": 4,"name": "Submenu 1 OF 2","url": "teste"},{"id": 5,"name": "Submenu 2 OF 2","content": [{"id": 6,"name": "Sub submenu 1 OF 2","url": "teste"},{"id": 7,"name": "Sub submenu 2 OF 2","url": "teste"},]}]}]
console.log(findParent(items, 6));
You can do this with a recursive function that checks each child and returns the parent if the id matches:
const findParent = (id, obj) => {
for (const child of obj.content) {
if (child.id === id) return obj;
if (!child.content) continue;
const found = findParent(id, child);
if (found) return found;
}
return undefined;
}
const items = {content: [{
"id": 1,
"name": "Menu 1",
"content": [{
"id": 2,
"name": "Submenu 1 OF 1",
"url": "teste"
}]
},
{
"id": 3,
"name": "Menu 2",
"content": [{
"id": 4,
"name": "Submenu 1 OF 2",
"url": "teste"
},
{
"id": 5,
"name": "Submenu 2 OF 2",
"content": [{
"id": 6,
"name": "Sub submenu 1 OF 2",
"url": "teste"
},
{
"id": 7,
"name": "Sub submenu 2 OF 2",
"url": "teste"
},
]
}
]
}
]
}
console.log(findParent(2, items));
console.log(findParent(6, items));

how to compare the key in the array of object and modify it using javascript

I have two objects obj1 and obj2, how to loop through array key children and if code name matches, then add the name key in the object obj2, get the object.
How to loop through object of objects and match the key and push the key to get the new object in javascript
function newObject(obj1, obj2) {
var result = obj1.map(e => {
if ('children' in e)
e.children = e.children.map(child => {
if ('children' in child)
child.children = child.children.map(c => {
name: c.name
});
return child;
});
return e;
})
return result
}
var obj1 = [{
"id": 1,
"item": "node1",
"children": [{
"id": 2,
"code": "countries",
"title": "Country",
"children": [{
"cid": 12,
"code": "S1",
"name": "SG",
"children": [{
"id": 4,
"code": "C1",
"name": "City"
}]
},
{
"cid": 13,
"code": "S2",
"name": "TH"
}
]
},
{
"id": 2,
"code": "Groceries",
"title": "Grocery",
"children": [{
"cid": 11,
"code": "G1",
"name": "Fruits"
},
{
"cid": 10,
"code": "G2",
"name": "Vegetables"
}
]
}, {
"id": 3,
"code": "lists",
"title": "Option"
}
]
}];
var obj2 = [{
id: 1,
code: "G1",
status: "active"
},
{
id: 2,
code: "S2",
status: "inactive"
},
{
id: 3,
code: "C1",
status: "active"
}
];
console.log(this.newObject(obj1, obj2));
Expected Output
[
{id:1, name: "Fruits",code:"G1", status:"active"},
{id:2, name: "TH",code:"S2", status:"inactive"},
{id:3, name: "city",code:"C1", status:"active"}
]
you can check this code
I fixed your object and you can find your expectation in the console

Categories