Get all its parent nodes path for each child nodes - javascript

Hi I have below code running, but I would like to add one more property called path which should consist all its parent node path
Expected output I need something as I have shown for cardTtile, so I need same for each node.
[
{
"id": "cardShop",
"key": "cardShop",
"title": "cardShop",
"selectable": false,
"path":cardShop"
"children": [
{
"id": "cardData",
"key": "cardData",
"title": "cardData",
"parentId": "cardShop",
"path":cardShop.cardData"
"selectable": false,
"children": [
{
"id": "cardTitle",
"key": "cardTitle",
"title": "cardTitle",
"parentId": "cardData",
"path":cardShop.cardData.cardTitle"
"isLeaf": true
},
{
"id": "cardType",
"key": "cardType",
"title": "cardType",
"parentId": "cardData",
"isLeaf": true
},
{
"id": "dtmProductName",
"key": "dtmProductName",
"title": "dtmProductName",
"parentId": "cardData",
"isLeaf": true
},
{
"id": "viewAllCards",
"key": "viewAllCards",
"title": "viewAllCards",
"parentId": "cardData",
"selectable": false,
"children": [
{
"id": "url",
"key": "url",
"title": "url",
"parentId": "viewAllCards",
"isLeaf": true
},
{
"id": "text",
"key": "text",
"title": "text",
"parentId": "viewAllCards",
"isLeaf": true
}
]
}
]
},
{
"id": "eligibilityChecker",
"key": "eligibilityChecker",
"title": "eligibilityChecker",
"parentId": "cardShop",
"selectable": false,
"children": [
{
"id": "header",
"key": "header",
"title": "header",
"parentId": "eligibilityChecker",
"isLeaf": true
},
{
"id": "subHeader",
"key": "subHeader",
"title": "subHeader",
"parentId": "eligibilityChecker",
"isLeaf": true
},
{
"id": "bulletPoints",
"key": "bulletPoints",
"title": "bulletPoints",
"parentId": "eligibilityChecker",
"isLeaf": true
}
]
}
]
}
]
I have below running code example here. I tried to persist parentKey recursively but its not giving me expected output.
const transform = data => {
const loop = (data, parent) => Object.entries(data).map(([key, value]) => {
let additional = parent? {
parentId: parent
}:{}
if(typeof value === 'object' && !Array.isArray(value)){
additional = {
...additional,
selectable: false,
children: loop(value, key)
}
}else{
additional.isLeaf = true
}
return {
id: key,
key,
title: key,
...additional
}
})
return loop(data)
}
let jsonObj = {
"data": {
"cardShop": {
"cardData": {
"cardTitle": "The Platinum Card<sup>®</sup>",
"cardType": "credit-cards",
"dtmProductName": "PlatinumCard",
"viewAllCards": {
"url": "credit-cards/all-cards",
"text": "All Cards"
}
},
"eligibilityChecker": {
"header": "Check your eligibility",
"subHeader": "The Platinum Card®",
"bulletPoints": [
"Only takes a couple of minutes to complete",
"Will not impact your credit rating",
"Allows you to apply with confidence"
]
}
}
}
}
console.log(transform(jsonObj.data))
]
You suggestion would be appreciated
Thanks

You could take another variable for path and add the actual key to it.
const transform = data => {
const loop = (data, parentId, previousPath = '') => Object
.entries(data)
.map(([key, value]) => {
const
additional = parentId ? { parentId } : {},
path = previousPath + (previousPath && '.') + key;
Object.assign(
additional,
value && typeof value === 'object' && !Array.isArray(value)
? { selectable: false, children: loop(value, key, path) }
: { isLeaf: true }
);
return { id: key, key, title: key, path, ...additional };
});
return loop(data);
}
const data = { cardShop: { cardData: { cardTitle: "The Platinum Card<sup>®</sup>", cardType: "credit-cards", dtmProductName: "PlatinumCard", viewAllCards: { url: "credit-cards/all-cards", text: "All Cards" } }, eligibilityChecker: { header: "Check your eligibility", subHeader: "The Platinum Card®", bulletPoints: ["Only takes a couple of minutes to complete", "Will not impact your credit rating", "Allows you to apply with confidence"] } } };
console.log(transform(data));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related

How to group keys from a nested object?

Hya 👋
Suppose we have a dynamic object like so:
[
{
"object": "block",
"id": "089cd0d8-ccbf-4e9e-97a6",
"parent": {
"type": "page_id",
"page_id": "d4b96daf-47a3-4a04-b200"
},
"type": "child_database",
"child_database": {
"title": "Hero"
}
},
{
"object": "page",
"id": "d3022361-96d2-4e15-999e",
"parent": {
"type": "database_id",
"database_id": "089cd0d8-ccbf-4e9e-97a6"
},
},
{
"object": "block",
"id": "a0cba166-1787-4e30-8cc3",
"parent": {
"type": "page_id",
"page_id": "d3022361-96d2-4e15-999e"
},
"type": "heading_1",
"heading_1": {
"rich_text": [
{
"type": "text",
"text": {
"content": "Introduction",
"link": null
},
"plain_text": "Introduction",
"href": null
}
],
}
},
{
"object": "block",
"id": "dbfdd892-8c04-4de3-bf0e",
"parent": {
"type": "page_id",
"page_id": "d3022361-96d2-4e15-999e"
},
"type": "heading_2",
"heading_2": {
"rich_text": [
{
"type": "text",
"text": {
"content": "This is introduction section",
"link": null
},
"plain_text": "This is introduction section",
"href": null
}
],
}
}
]
I would like to reconstruct this object by grouping them based on parent-child like relationship. Since every object has "parent" prop.
The desired result should be like so, where the elements that share the same parent are grouped under child array.
{
"d4b96daf-47a3-4a04-b200": {
"object": "block",
"id": "089cd0d8-ccbf-4e9e-97a6",
"type": "child_database",
"child": [{
"d3022361-96d2-4e15-999e": {
"object": "page",
"child": [{
"a0cba166-1787-4e30-8cc3": {
"object": "block",
"type": "heading_1",
"heading_1": {
"rich_text": [{
"type": "text",
"text": {
"content": "Introduction",
"link": null
},
"plain_text": "Introduction",
"href": null
}]
}
}
},
{
"dbfdd892-8c04-4de3-bf0e": {
"object": "block",
"type": "heading_1",
"heading_2": {
"rich_text": [{
"type": "text",
"text": {
"content": "This is introduction section",
"link": null
},
"plain_text": "This is introduction section",
"href": null
}]
}
}
}
]
}
}]
}
}
Current workaround
/**
* Generator that traverses through nested object
*/
function* traverse(xs: any[] = []): any {
for (let x of xs) {
yield x
yield* traverse(x.child || [])
}
}
/**
* If the property exists in the nested object, then return node
*/
const deepFind = (block: any, pred: any) => (obj: any) => {
for (let node of traverse([obj])) {
if (pred(node)) {
return node
}
}
}
const findById = (block: any) => (obj: any) => deepFind(block, (o: any) => o[block.id])(obj)
export default async function group(pages: Page[]) {
// stuck here 🙏
}
You can do this linearly: create a Map id=>object, iterate the list, if the parent is already on the map, add your object to the parent.child, otherwise create a placeholder object with the parent's id.
let m = new Map()
for (let obj of data) {
let dummy = {id: 'dummy', child: []}
let oid = obj.id
m.set(oid, {...dummy, ...obj, ...m.get(oid)})
let pid = obj.parent.page_id // or whatever depending on type
m.set(pid, m.get(pid) ?? dummy)
m.get(pid).child.push(obj)
}
In the end, the m.values() will contain a flat list of objects with child arrays properly populated.

Finding ID in nested array of objects

I'm still new to recursive functions but I'm having trouble returning the object once found to a variable (currently searching based on ID). I've included a dataset below and what I have so far. The recursive function finds the correct matching item, but when it returns it, it just returns undefined to the variable. I have tried the solution here and also get the same problem I have where it just returns undefined instead of the object. Any help/pointers would be great!
const data = {
"navItems": [
{
"type": "directory",
"id" : 1,
"name": "Nav Title 1",
"children": [
{
"downloadUrl": "",
"content": "",
"id" : 2,
"type": "file",
"name": "File 1.pdf"
},
{
"downloadUrl": "",
"content": "",
"type": "file",
"id" : 3,
"name": "File 2.pdf"
},
{
"type": "directory",
"name": "Sub Title 1",
"id" : 4,
"children": [
{
"downloadUrl": "",
"content": "",
"type": "file",
"id" : 5,
"name": "Sub File 1.pdf"
},
{
"downloadUrl": "",
"content": "",
"type": "file",
"id" : 6,
"name": "Sub File 2.docx"
}
]
},
{
"type": "directory",
"name": "Sub Title 2",
"id" : 7,
"children": [
{
"type": "directory",
"id" : 8,
"name": "Sub Sub Title 1",
"children": [
{
"downloadUrl": "",
"id" : 9,
"content": "",
"type": "file",
"name": "Sub Sub File 1.pdf"
},
{
"downloadUrl": "",
"content": "",
"type": "file",
"id" : 10,
"name": "Sub Sub File 2.pdf"
}
]
},
{
"type": "directory",
"name": "Sub Sub Title 2",
"id" : 11,
"children": [
{
"downloadUrl": "",
"content": "",
"id" : 12,
"type": "file",
"name": "Sub Sub File 1.pdf"
},
{
"downloadUrl": "",
"content": "",
"id" : 13,
"type": "file",
"name": "Sub Sub File 2.pdf"
}
]
}
]
}
]
}
]
}
/* console.log(navigationConfig);*/
const searchNavItems = (navItem) => {
if (navItem.id == 10) {
console.log(navItem);
return navItem;
} else {
if (navItem.hasOwnProperty("children") && navItem.children.length > 0 && navItem.type == "directory") {
navItem.children.map(child => searchNavItems(child))
} else {
return false;
}
}
};
let dataItem = data.navItems.forEach((item => {
let nav = searchNavItems(item);
console.log(nav);
}))
console.log(dataItem)
in your fn there are couple of problems
when you are maping over children you are not returning the array of children
forEach does not return anything () => void, so you will need to create a new variable to hold that value
let dataItem;
data.navItems.forEach((item) => {
console.log(searchNavItems(item));
dataItem = searchNavItems(item);
});
hope this helps
Presented below is one possible way to achieve the desired objective.
Code Snippet
const mySearch = (needle, hayStack) => (
hayStack.some(({ id }) => id === needle)
? (
{children, ...rest} = hayStack.find(({ id }) => id === needle),
[{...rest}]
)
: hayStack.flatMap(
({ children = [] }) => mySearch(needle, children)
)
);
/* explanation of the above method
// method to search for element/s with given "id"
// finding "needle" (ie "id") in hayStack (ie, "array" of objects)
const mySearch = (needle, hayStack) => (
// check if needle exists in current array
hayStack.some(({ id }) => id === needle)
? ( // find the matching array elt, destructure to access
// "children" and "rest" props.
// send the props other than "children"
{children, ...rest} = hayStack.find(({ id }) => id === needle),
[{...rest}]
) // if needle is not present in current array
// try searching in the inner/nested "children" array
: hayStack.flatMap( // use ".flatMap()" to avoid nested return
// recursive call to "mySearch" with "children" as the hayStack
({ children = [] }) => mySearch(needle, children)
)
);
*/
const data = {
"navItems": [{
"type": "directory",
"id": 1,
"name": "Nav Title 1",
"children": [{
"downloadUrl": "",
"content": "",
"id": 2,
"type": "file",
"name": "File 1.pdf"
},
{
"downloadUrl": "",
"content": "",
"type": "file",
"id": 3,
"name": "File 2.pdf"
},
{
"type": "directory",
"name": "Sub Title 1",
"id": 4,
"children": [{
"downloadUrl": "",
"content": "",
"type": "file",
"id": 5,
"name": "Sub File 1.pdf"
},
{
"downloadUrl": "",
"content": "",
"type": "file",
"id": 6,
"name": "Sub File 2.docx"
}
]
},
{
"type": "directory",
"name": "Sub Title 2",
"id": 7,
"children": [{
"type": "directory",
"id": 8,
"name": "Sub Sub Title 1",
"children": [{
"downloadUrl": "",
"id": 9,
"content": "",
"type": "file",
"name": "Sub Sub File 1.pdf"
},
{
"downloadUrl": "",
"content": "",
"type": "file",
"id": 10,
"name": "Sub Sub File 2.pdf"
}
]
},
{
"type": "directory",
"name": "Sub Sub Title 2",
"id": 11,
"children": [{
"downloadUrl": "",
"content": "",
"id": 12,
"type": "file",
"name": "Sub Sub File 1.pdf"
},
{
"downloadUrl": "",
"content": "",
"id": 13,
"type": "file",
"name": "Sub Sub File 2.pdf"
}
]
}
]
}
]
}]
};
console.log(
'data for id: 10\n',
mySearch(10, data.navItems)?.[0]
);
console.log(
'data for id: 13\n',
mySearch(13, data.navItems)?.[0]
);
console.log(
'data for id: 9\n',
mySearch(9, data.navItems)?.[0]
);
console.log(
'data for id: 3\n',
mySearch(3, data.navItems)?.[0]
);
.as-console-wrapper { max-height: 100% !important; top: 0 }
Explanation
Inline comments added to the snippet above.

How to add object to specific place in JavaScript?

I am using a library React simple chatbot and add data from database, but the problem is i have array like below
Array from Database
[{
"id": 1,
"message": "What is your name?",
"type": "text",
"trigger": "2"
}, {
"id": 2,
"message": "What is your age?",
"type": "text",
"trigger": "3"
}, {
"id": 3,
"message": "What is your date of birth?",
"type": "text",
"trigger": "1"
}]
But i need something like below
[{
"id": 1,
"message": "What is your name?",
"type": "text",
"trigger": "2"
}, {
"id": 2,
"user": true,
"trigger": 3
}, {
"id": 3,
"message": "What is your age?",
"type": "text",
"trigger": "4"
}, {
"id": 4,
"user": true,
"trigger": 5
}, {
"id": 5,
"message": "What is your date of birth?",
"type": "text",
"trigger": "6"
}, {
"id": 6,
"user": true,
"trigger": 1
}]
Please help me to create array like this. I write some code, but doesn't work for me. My code print duplicate ids. Basically i want to pass object after every object with increment id.
Code
fetch("api_url_here")
.then((res) => {
return res.json();
})
.then((data) => {
const steps = data.map((res, index) => {
return {
id: index,
message: res.question,
type: res.type,
trigger: res.trigger,
};
});
var array = [];
var trigger = 1;
steps.forEach((step, index) => {
index = index;
array.push(step);
if (step.type == "text") {
array.push({
id: trigger + 1,
user: true,
trigger: trigger,
});
}
trigger++;
});
document.getElementById("json").append(JSON.stringify(array));
})
Current Output
[{
"id": 0,
"message": "What is your name?",
"type": "text",
"trigger": "2"
}, {
"id": 2,
"user": true,
"trigger": 1
}, {
"id": 1,
"message": "What is your age?",
"type": "text",
"trigger": "3"
}, {
"id": 3,
"user": true,
"trigger": 2
}, {
"id": 2,
"message": "What is your date of birth?",
"type": "text",
"trigger": "1"
}, {
"id": 4,
"user": true,
"trigger": 3
}]
Any solution appreciated!
You only need to add this as a final step to correct the id and trigger
const almost = [{
"id": 0,
"message": "What is your name?",
"type": "text",
"trigger": "2"
}, {
"id": 2,
"user": true,
"trigger": 1
}, {
"id": 1,
"message": "What is your age?",
"type": "text",
"trigger": "3"
}, {
"id": 3,
"user": true,
"trigger": 2
}, {
"id": 2,
"message": "What is your date of birth?",
"type": "text",
"trigger": "1"
}, {
"id": 4,
"user": true,
"trigger": 3
}]
const final = almost.map( (obj,index) => {
const newObj = {};
Object.assign(newObj,
obj,
{
"id":index+1,
"trigger": index+2
}
);
return newObj;
});
final[final.length-1].trigger = 1;
console.log(final)
EDIT: to make it clear, your code would look like:
fetch("api_url_here")
.then((res) => {
return res.json();
})
.then((data) => {
const steps = data.map((res, index) => {
return {
id: index,
message: res.question,
type: res.type,
trigger: res.trigger,
};
});
var array = [];
var trigger = 1;
steps.forEach((step, index) => {
index = index;
array.push(step);
if (step.type == "text") {
array.push({
id: trigger + 1,
user: true,
trigger: trigger,
});
}
trigger++;
});
array = array.map( (obj,index) => {
const newObj = {};
Object.assign(newObj,
obj,
{
"id":index+1,
"trigger": index+2
}
);
return newObj;
});
array[array.length-1].trigger = 1;
document.getElementById("json").append(JSON.stringify(array));
})

Convert one Multidimensional JSON array to another

I have the following input object
{
"id": 1,
"isLeaf": false,
"name": "New rule",
"pid": 0,
"dragDisabled": true,
"children": [
{
"id": "new1",
"value": "data1",
"then": false,
"type": "set",
"forEach": false,
"pid": 1
},
{
"id": "new2",
"value": "data2",
"then": true,
"type": "if",
"forEach": false,
"pid": 1,
"children": [
{
"id": "new3",
"type": "Then",
"enableElse": true,
"pid": "new2",
"children": [
{
"id": "new5",
"value": "data3",
"then": false,
"type": "fuzzy_search",
"forEach": false,
"pid": "new3"
}
]
},
{
"id": "new4",
"type": "Else",
"enableElse": true,
"pid": "new2",
"children": [
{
"id": "new6",
"value": "data4",
"then": false,
"type": "return",
"forEach": false,
"pid": "new4"
}
]
}
]
}
]
}
I need to convert it into the following json
[
{
"id": "new1",
"condition": "data1"
},
{
"id": "new2",
"condition": "data2",
"then": [{
"id": "new5",
"condition": "data3"
}],
"else": [{
"id": "new6",
"condition": "data4"
}]
}
]
I have to recursively iterate through all existing inner child array of the input json array to formulate the output.
Following is the partially implemented code for the functionality.
ruleJSONFormatter = (request, parentItem, innerJSON) => {
try {
var outerObject = request;
if (outerObject.children && outerObject.children.length) {
var innerArray = outerObject.children;
// second iteration with inner children
innerArray.forEach((innerItem, index) => {
let parentObj = {};
let recursiveObj = {}; let thenArray = [];
recursiveObj['condition'] = innerItem.value && innerItem.value != undefined ? innerItem.value.formatedData : {};
recursiveObj['type'] = innerItem.type;
recursiveObj['id'] = innerItem.id;
recursiveObj['pid'] = innerItem.pid;
if (innerItem.children && innerItem.children != undefined && innerItem.children.length) {
switch (innerItem.type) {
case 'if':
recursiveObj['then'] = [];
recursiveObj['else'] = [];
}
if (Object.keys(parentObj).length == 0) {
parentObj = recursiveObj;
} else {
}
ruleJSONFormatter(innerItem, parentItem, parentObj)
} else {
if (Object.keys(parentObj).length == 0)
responseArray.push(innerJSON);
}
});
}
else {
console.log("No Values Inside the Formated Data ")
}
console.log("output-----------");
console.log(JSON.stringify(responseArray));
return responseArray
} catch (error) {
console.log('((((((((((((((((((((((((((', error)
}
}
final output array has a condition key which binds the value key from the input json and 'then' key which contains the multiple successive inner children array which is the success condition for type 'if' object. similar is the case for 'else' key in output
I find it hard to recursively call the same function to generate the desired output. the problem arises when there are deep nesting in the children array.Any help is appreciated.Thanks.

flattening nested json object

[
{
"children": [
{
"children": [
{
"dateAdded": 1493033302670,
"id": "1534",
"index": 0,
"parentId": "1",
"title": "data1",
"url": "data2"
},
{
"children": [
{
"dateAdded": 1489571506844,
"id": "1451",
"index": 0,
"parentId": "1401",
"title": "data3",
"url": "data4"
}
],
"dateAdded": 1490363326576,
"dateGroupModified": 1490363326576,
"id": "1401",
"index": 1,
"parentId": "1",
"title": "daily"
},
{
"children": [
{
"dateAdded": 1481787664555,
"id": "1429",
"index": 0,
"parentId": "1407",
"title": "data56",
"url": "data"
},
{
"dateAdded": 1483365608504,
"id": "1430",
"index": 1,
"parentId": "1407",
"title": "data34",
"url": "data55"
}
]
}
]
}
]
}
]
This is a representation of Chrome bookmarks data.
If the object has url property it means that is a bookmark. If it does not have url property it is a folder.
It is a tree structure.
I would like to create flatten object with additional property named type. Like:
[
{
"dateAdded": 1489571506844,
"id": "1451",
"index": 0,
"parentId": "1401",
"title": "title",
"url": "some url",
"type": "bookmark"
},
{
"dateAdded": 1489571506844,
"id": "1451",
"index": 0,
"parentId": "1402",
"title": "title2",
"url": "some url2"
"type": "folder"
}
]
Thanks in advance.
You could use an iterative and recursive approach for getting flat data.
function flatten(array) {
var result = [];
array.forEach(function iter(o) {
var temp = {},
keys = Object.keys(o);
if (keys.length > 1) {
keys.forEach(function (k) {
if (k !== 'children') {
temp[k] = o[k];
}
});
temp.type = 'url' in o ? 'bookmark' : 'folder';
result.push(temp);
}
Array.isArray(o.children) && o.children.forEach(iter);
});
return result;
}
var data = [{ children: [{ children: [{ dateAdded: 1493033302670, id: "1534", index: 0, parentId: "1", title: "data1", url: "data2" }, { children: [{ dateAdded: 1489571506844, id: "1451", index: 0, parentId: "1401", title: "data3", url: "data4" }], dateAdded: 1490363326576, dateGroupModified: 1490363326576, id: "1401", index: 1, parentId: "1", title: "daily" }, { children: [{ dateAdded: 1481787664555, id: "1429", index: 0, parentId: "1407", title: "data56", url: "data" }, { dateAdded: 1483365608504, id: "1430", index: 1, parentId: "1407", title: "data34", url: "data55" }] }] }] }];
console.log(flatten(data));
.as-console-wrapper { max-height: 100% !important; top: 0; }
I've made a function that iterates through an array containing objects. If a given object has a property called children, the function calls itself. If it doesn't, then it gets pushed to a new array flattenedBookmarks.
The Solution
var flattenedBookmarks = [];
flattenBookmarks(bookmarks);
function flattenBookmarks(bookmarks) {
for (var i = 0; i < bookmarks.length; i++) {
var potentialBookmark = bookmarks[i];
if (potentialBookmark.hasOwnProperty("url")) {
potentialBookmark.type = "bookmark";
} else {
potentialBookmark.type = "folder";
}
if (potentialBookmark.hasOwnProperty("children")) {
flattenBookmarks(potentialBookmark.children);
if (potentialBookmark.hasOwnProperty("dateGroupModified")) {
flattenedBookmarks.push(potentialBookmark);
}
} else {
flattenedBookmarks.push(potentialBookmark);
}
}
}
You should probably be returning the flattened array from the function instead of storing it in a new global array flattenedBookmarks, but at least this will get you started.
https://jsfiddle.net/s9ur35re/
The example shows how to do it
data = [
{
"children": [
{
"children": [
{
"dateAdded": 1493033302670,
"id": "1534",
"index": 0,
"parentId": "1",
"title": "data1",
"url": "data2"
},
{
"children": [
{
"dateAdded": 1489571506844,
"id": "1451",
"index": 0,
"parentId": "1401",
"title": "data3",
"url": "data4"
}
],
"dateAdded": 1490363326576,
"dateGroupModified": 1490363326576,
"id": "1401",
"index": 1,
"parentId": "1",
"title": "daily"
},
{
"children": [
{
"dateAdded": 1481787664555,
"id": "1429",
"index": 0,
"parentId": "1407",
"title": "data56",
"url": "data"
},
{
"dateAdded": 1483365608504,
"id": "1430",
"index": 1,
"parentId": "1407",
"title": "data34",
"url": "data55"
}
]
}
]
}
]
}
];
data2 = [];
function search(data) {
for (n in data) {
if (typeof data[n] == 'object') {
if (data[n].id != undefined) {
if (data[n].url != undefined) {
data[n].type="folder";
} else {
data[n].type="bookmark";
}
data2.push(data[n]);
}
search(data[n]);
}
}
}
search(data);
console.log(data2);

Categories

Resources