validate json array schema - javascript

guys i have this json
var menu = [{
name: 'Computers',
children: [{
name: 'Notebook'
children: [{
name: 'Apple'
}, {
name: 'Windows'
}]
}, {
name: Tablets
children: [{
name: 'Apple'
}, {
name: 'Android'
}, {
name: 'Windows'
}]
}]
}, {
name: 'Phones',
children: [{
name: 'Android'
children: [{
name: 'Samsung'
}, {
name: 'Nokia'
}, {
name: 'Lenovo'
}]
}, {
name: 'Windows Phones'
children: [{
name: 'Microsoft'
}, {
name: 'Nokia'
}]
}]
}, {
name: 'Cameras',
children: [{
name: 'Digital'
children: [{
name: 'Nikon'
}, {
name: 'Fuji'
}]
}, {
name: 'DSLR'
children: [{
name: 'Canon'
}, {
name: 'Nikon'
}]
}]
}];
it says it is not valid json ... so how to make it valid json ??
any help would be appreciated ... thanks a lot
btw i am beginner so please help me
any suggestions ?? thanks again :)

You have some missing commas, where noted and a suposed to be a string without delimiters in your object literal.
var menu = [{
name: 'Computers',
children: [{
name: 'Notebook', // missing ,
children: [{
name: 'Apple'
}, {
name: 'Windows'
}]
}, {
name: 'Tablets', // missing string delimiter and comma
children: [{
name: 'Apple'
}, {
name: 'Android'
}, {
name: 'Windows'
}]
}]
}, {
name: 'Phones',
children: [{
name: 'Android', // missing ,
children: [{
name: 'Samsung'
}, {
name: 'Nokia'
}, {
name: 'Lenovo'
}]
}, {
name: 'Windows Phones', // missing ,
children: [{
name: 'Microsoft'
}, {
name: 'Nokia'
}]
}]
}, {
name: 'Cameras',
children: [{
name: 'Digital', // missing ,
children: [{
name: 'Nikon'
}, {
name: 'Fuji'
}]
}, {
name: 'DSLR', // missing ,
children: [{
name: 'Canon'
}, {
name: 'Nikon'
}]
}]
}];
console.log(menu);
.as-console-wrapper { max-height: 100% !important; top: 0; }

There are two problems
After name property values, comma is missing (at various places)
Tablets is not in quotes
Correct syntax would be.
var menu = [{
name: 'Computers',
children: [{
name: 'Notebook',
children: [{
name: 'Apple'
}, {
name: 'Windows'
}]
}, {
name: 'Tablets',
children: [{
name: 'Apple'
}, {
name: 'Android'
}, {
name: 'Windows'
}]
}]
}, {
name: 'Phones',
children: [{
name: 'Android',
children: [{
name: 'Samsung'
}, {
name: 'Nokia'
}, {
name: 'Lenovo'
}]
}, {
name: 'Windows Phones',
children: [{
name: 'Microsoft'
}, {
name: 'Nokia'
}]
}]
}, {
name: 'Cameras',
children: [{
name: 'Digital',
children: [{
name: 'Nikon'
}, {
name: 'Fuji'
}]
}, {
name: 'DSLR',
children: [{
name: 'Canon'
}, {
name: 'Nikon'
}]
}]
}];
You can copy your code is chrome's console to see where the error is.

you need to put double quotes on key an value like this "key" : "value"
[{
"name": "Computers",
"children": [{
"name": "Notebook",
"children": [{
"name": "Apple"
}, {
"name": "Windows"
}]
}, {
"name": "Tablets",
"children": [{
"name": "Apple"
}, {
"name": "Android"
}, {
"name": "Windows"
}]
}]
}]
And after name property values, comma is missing (at various places)

key and value should be wrapped by double quotes
copy paste the code validate here https://jsonformatter.curiousconcept.com/
[
{
"name":"Computers",
"children":[
{
"name":"Notebook",
"children":[
{
"name":"Apple"
},
{
"name":"Windows"
}
]
},
{
"name":"Tablets",
"children":[
{
"name":"Apple"
},
{
"name":"Android"
},
{
"name":"Windows"
}
]
}
]
},
{
"name":"Phones",
"children":[
{
"name":"Android",
"children":[
{
"name":"Samsung"
},
{
"name":"Nokia"
},
{
"name":"Lenovo"
}
]
},
{
"name":"Windows Phones",
"children":[
{
"name":"Microsoft"
},
{
"name":"Nokia"
}
]
}
]
},
{
"name":"Cameras",
"children":[
{
"name":"Digital",
"children":[
{
"name":"Nikon"
},
{
"name":"Fuji"
}
]
},
{
"name":"DSLR",
"children":[
{
"name":"Canon"
},
{
"name":"Nikon"
}
]
}
]
}
]

Related

How to I achieve nesting for objects having ParentKey?

I have an array of objects with Name, Key in all objects and ParentKey in some of the objects.
I want to group objects by unique 'Key' excluding those which have 'ParentKey'. The objects having ParentKey should be nested as reflected in required ans.
Initial Input :-
const arr = [
{
Name: 'Manage Leads',
Key: 'Manage Leads',
},
{
Name: 'Dashboard',
Key: 'Dashboard',
},
{
Name: 'Smart Views',
Key: 'Smart Views',
},
{
Name: 'Lead Details',
Key: 'Lead Details',
},
{
Name: 'Opportunity Details',
Key: 'Opportunity Details',
},
{
Name: 'Header',
Key: 'Header',
},
{
Name: 'Settings',
Key: 'Settings',
},
{
Name: 'Test 1',
Key: 'Test1Key',
},
{
Name: 'Test 1.1',
Key: 'Test1.1Key',
ParentKey: 'Test1',
},
{
Name: 'Test 1.2',
Key: 'Test1.2Key',
ParentKey: 'Test1',
},
{
Name: 'Test 1.1.1',
Key: 'Test1.1.1Key',
ParentKey: 'Test 1.1',
},
{
Name: 'Test 1.1.2',
Key: 'Test1.1.2Key',
ParentKey: 'Test 1.1',
},
{
Name: 'Test 1.2.1',
Key: 'Test1.2.1Key',
ParentKey: 'Test 1.2',
},
];
Required Output :-
[
{
groupName: 'Manage Leads',
actionsArr: [{ Name: 'Manage Leads', Key: 'Manage Leads' }],
},
{
groupName: 'Dashboard',
actionsArr: [{ Name: 'Dashboard', Key: 'Dashboard' }],
},
{
groupName: 'Smart Views',
actionsArr: [{ Name: 'Smart Views', Key: 'Smart Views' }],
},
{
groupName: 'Lead Details',
actionsArr: [{ Name: 'Lead Details', Key: 'Lead Details' }],
},
{
groupName: 'Opportunity Details',
actionsArr: [
{
Name: 'Opportunity Details',
Key: 'Opportunity Details',
},
],
},
{
groupName: 'Header',
actionsArr: [{ Name: 'Header', Key: 'Header' }],
},
{
groupName: 'Settings',
actionsArr: [{ Name: 'Settings', Key: 'Settings' }],
},
{
groupName: 'Test1Key',
actionsArr: [
{
Name: 'Test 1',
Key: 'Test1Key',
subActions: [
{
Name: 'Test 1.1',
Key: 'Test1.1',
ParentKey: 'Test1Key',
subActions: [
{
Name: 'Test 1.1.1',
Key: 'Test1.1.1Key',
ParentKey: 'Test 1.1',
},
{
Name: 'Test 1.1.2',
Key: 'Test1.1.2Key',
ParentKey: 'Test 1.1',
},
],
},
{
Name: 'Test 1.2',
Key: 'Test1.2',
ParentKey: 'Test1Key',
subActions: [
{
Name: 'Test 1.2.1',
Key: 'Test1.2.1Key',
ParentKey: 'Test 1.2',
},
],
},
],
},
],
},
];
I was able to group by unique Key with the follwoing code but i'm not able to nest the objects which have ParentKey.
const groupNames = [...new Set(actions.map((item) => item.GroupKey))];
const actionsList = groupNames.map((groupName) => {
const actionsArr = actions.filter((act) => act.GroupKey === groupName);
return { label: groupName, value: actionsArr }});
I found some inconsistencies between Key and ParentKey for the given data.
I have fixed the inconsistencies in the input data, and I would be using the same.
Here is the solution that worked for me.
const arr = [
{
Name: "Manage Leads",
Key: "Manage Leads",
},
{
Name: "Dashboard",
Key: "Dashboard",
},
{
Name: "Smart Views",
Key: "Smart Views",
},
{
Name: "Lead Details",
Key: "Lead Details",
},
{
Name: "Opportunity Details",
Key: "Opportunity Details",
},
{
Name: "Header",
Key: "Header",
},
{
Name: "Settings",
Key: "Settings",
},
{
Name: "Test 1",
Key: "Test1Key",
},
{
Name: "Test 1.1",
Key: "Test1.1Key",
ParentKey: "Test 1",
},
{
Name: "Test 1.2",
Key: "Test1.2Key",
ParentKey: "Test 1",
},
{
Name: "Test 1.1.1",
Key: "Test1.1.1Key",
ParentKey: "Test 1.1",
},
{
Name: "Test 1.1.2",
Key: "Test1.1.2Key",
ParentKey: "Test 1.1",
},
{
Name: "Test 1.2.1",
Key: "Test1.2.1Key",
ParentKey: "Test 1.2",
},
];
//recursively look for the child and append child to parent
const appendChild = (parent, arr) => {
for (let index = 0; index < arr.length; index++) {
const childElement = arr[index];
if (childElement.ParentKey == parent.Name) {
appendChild(childElement, arr);
if (parent.subActions) {
parent.subActions.push(childElement);
} else {
parent.subActions = [childElement];
}
//remove the child from that list and match the index
arr.splice(index, 1);
index--;
}
}
};
//convert data into a parent-child hierarchy
const convert = (arr) => {
for (const parent of arr) {
appendChild(parent, arr);
}
//filter out items which has been already added as child/subActions
return arr.filter((x) => !Boolean(x.ParentKey));
};
const groupBy = (items, callback) => {
const groupedData = items.reduce(
(acc, value, index) => (
(acc[callback(value, index, items)] ||= []).push(value), acc
),
{}
);
//convert grouped data as the required output
return Object.entries(groupedData).map(([key, value]) => ({
groupName: key,
actionsArr: value,
}));
};
const data = groupBy(convert(arr), (x) => x.Name);
console.log(JSON.stringify(data, null, 2));
Output:
[
{
"groupName": "Manage Leads",
"actionsArr": [
{
"Name": "Manage Leads",
"Key": "Manage Leads"
}
]
},
{
"groupName": "Dashboard",
"actionsArr": [
{
"Name": "Dashboard",
"Key": "Dashboard"
}
]
},
{
"groupName": "Smart Views",
"actionsArr": [
{
"Name": "Smart Views",
"Key": "Smart Views"
}
]
},
{
"groupName": "Lead Details",
"actionsArr": [
{
"Name": "Lead Details",
"Key": "Lead Details"
}
]
},
{
"groupName": "Opportunity Details",
"actionsArr": [
{
"Name": "Opportunity Details",
"Key": "Opportunity Details"
}
]
},
{
"groupName": "Header",
"actionsArr": [
{
"Name": "Header",
"Key": "Header"
}
]
},
{
"groupName": "Settings",
"actionsArr": [
{
"Name": "Settings",
"Key": "Settings"
}
]
},
{
"groupName": "Test 1",
"actionsArr": [
{
"Name": "Test 1",
"Key": "Test1Key",
"subActions": [
{
"Name": "Test 1.1",
"Key": "Test1.1Key",
"ParentKey": "Test 1",
"subActions": [
{
"Name": "Test 1.1.1",
"Key": "Test1.1.1Key",
"ParentKey": "Test 1.1"
},
{
"Name": "Test 1.1.2",
"Key": "Test1.1.2Key",
"ParentKey": "Test 1.1"
}
]
},
{
"Name": "Test 1.2",
"Key": "Test1.2Key",
"ParentKey": "Test 1",
"subActions": [
{
"Name": "Test 1.2.1",
"Key": "Test1.2.1Key",
"ParentKey": "Test 1.2"
}
]
}
]
}
]
}
]

JS filtering an Array item through a value in a nested Array

I can't figure out how to properly use .filter() to find an object in an Array by searching for a value in its nested Array.
I have the following data:
const orders = [
{
id: 1,
items: [
{
itemId: "abc",
},
{
itemId: "def",
},
],
},
{
id: 2,
items: [
{
itemId: "jkl",
},
{
itemId: "mno",
},
],
},
{
id: 3,
items: [
{
itemId: "abc",
},
{
itemId: "xyz",
},
],
},
];
I have the needed itemId: "abc" which I need to use to find all the objects that have items that also have the Id of "abc", so that the result is this:
[
{
id: 1,
items: [
{
itemId: "abc",
},
{
itemId: "def",
},
],
},
{
id: 3,
items: [
{
itemId: "abc",
},
{
itemId: "xyz",
},
],
},
]
So far, I've tried the following:
orders &&
orders.filter((order) => {
return order.items.filter((item) => item.itemId === "abc");
});
But it doesn't seem to work. What am I missing here?
Chris G beat me to it in the comments but he is right, you need to use order.items.some in your inner function:
const orders = [{
id: 1,
items: [{
itemId: "abc",
},
{
itemId: "def",
},
],
},
{
id: 2,
items: [{
itemId: "jkl",
},
{
itemId: "mno",
},
],
},
{
id: 3,
items: [{
itemId: "abc",
},
{
itemId: "xyz",
},
],
},
]
var ans = orders.filter((order) => {
return order.items.some((item) => item.itemId === "abc");
});
console.log(ans)
const orders = [{
id: 1,
items: [{
itemId: "abc",
},
{
itemId: "def",
},
],
},
{
id: 2,
items: [{
itemId: "jkl",
},
{
itemId: "mno",
},
],
},
{
id: 3,
items: [{
itemId: "abc",
},
{
itemId: "xyz",
},
],
},
];
const result = orders.filter(order =>
order.items.find(item => item.itemId === 'abc') !== undefined
)
console.log(result);

How to return data if value does not exist in the nested array of objects using Higher order functions

Suppose I have a Nested array of objects like below:
let a = [{
title: "A123",
book: "A",
tags: [{
key: "Romantic",
ID: 1
}, {
key: "Sad",
ID: 2
},{
key: "Strange",
ID: 3
}]
}, {
title: "B123",
book: "B",
tags: [{
key: "Parody",
ID: 1
}, {
key: "Romantic",
ID: 2
},{
key: "Happy",
ID: 3
}]
}, {
title: "C123",
book: "C",
tags: [{
key: "Dark",
ID: 1
}, {
key: "Science Fiction",
ID: 2
}]
}, {
title: "D123",
book: "D",
tags: [{
key: "New Life",
ID: 1
}, {
key: "Science Fiction",
ID: 2
}]
}]
Now I am trying to get the output of those objects which does not contain the tags as 'Romantic'.
** Expected Output:**
{
title: "C123",
book: "C",
tags: [{
key: "Dark",
ID: 1
}, {
key: "Science Fiction",
ID: 2
}]
}, {
title: "D123",
book: "D",
tags: [{
key: "New Life",
ID: 1
}, {
key: "Science Fiction",
ID: 2
}]
}
I have tried the below from my end but it is returning all the elements. Is there a way to achieve the expected output?
a.filter( (ele) => ele.tags.filter( (eachTags) => eachTags.key !== 'Romantic'))
You can use every instead of the 2nd filter:
a.filter(book => book.tags.every(tag => tag.key !== "Romantic"));
Which is saying filter the array and exclude a book where any tag is Romantic.
Example:
let a = [{
title: "A123",
book: "A",
tags: [{
key: "Romantic",
ID: 1
}, {
key: "Sad",
ID: 2
},{
key: "Strange",
ID: 3
}]
}, {
title: "B123",
book: "B",
tags: [{
key: "Parody",
ID: 1
}, {
key: "Romantic",
ID: 2
},{
key: "Happy",
ID: 3
}]
}, {
title: "C123",
book: "C",
tags: [{
key: "Dark",
ID: 1
}, {
key: "Science Fiction",
ID: 2
}]
}, {
title: "D123",
book: "D",
tags: [{
key: "New Life",
ID: 1
}, {
key: "Science Fiction",
ID: 2
}]
}];
let notRomantic = a.filter(book => book.tags.every(tag => tag.key !== "Romantic"));
console.log(notRomantic);
Alternatively you could use Array.prototype.some():
let a = [
{title: "A123",book: "A",tags: [{key: "Romantic",ID: 1}, {key: "Sad",ID: 2},{key: "Strange",ID: 3}]},
{title: "B123",book: "B",tags: [{key: "Parody",ID: 1}, {key: "Romantic",ID: 2},{key: "Happy",ID: 3}]},
{title: "C123",book: "C",tags: [{key: "Dark",ID: 1}, {key: "Science Fiction",ID: 2}]},
{title: "D123",book: "D",tags: [{key: "New Life",ID: 1}, {key: "Science Fiction",ID: 2}]}]
console.log(a.filter(o=>!o.tags.some(t=>t.key==="Romantic")))
you can achieve this result using filter and some
const result = a.filter((obj) => !obj.tags.some((o) => o.key === "Romantic"));
let a = [
{
title: "A123",
book: "A",
tags: [
{
key: "Romantic",
ID: 1,
},
{
key: "Sad",
ID: 2,
},
{
key: "Strange",
ID: 3,
},
],
},
{
title: "B123",
book: "B",
tags: [
{
key: "Parody",
ID: 1,
},
{
key: "Romantic",
ID: 2,
},
{
key: "Happy",
ID: 3,
},
],
},
{
title: "C123",
book: "C",
tags: [
{
key: "Dark",
ID: 1,
},
{
key: "Science Fiction",
ID: 2,
},
],
},
{
title: "D123",
book: "D",
tags: [
{
key: "New Life",
ID: 1,
},
{
key: "Science Fiction",
ID: 2,
},
],
},
];
const result = a.filter((obj) => !obj.tags.some((o) => o.key === "Romantic"));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Find matching nodes in a tree with full path

I have an array of objects like this
[{
name: "Peter",
children: [{
name: "John",
children: [{
name: "Joseph",
children: []
}]
}, {
name: "Shawn",
children: [{
name: "Joseph",
children: []
}]
}]
}, {
name: "Carl",
children: [{
name: "Sam",
children: [{
name: "JohnXX",
children: []
}]
}]
}]
Where each person can have multiple children and each of these children can have any number of children and so on.
I want to retain the full path with matching children and exclude non matching children.For example if I search for John output should be like this
[{
name: "Peter",
children: [{
name: "John",
children: [{
name: "Joseph",
children: []
}]
}]
}, {
name: "Carl",
children: [{
name: "Sam",
children: [{
name: "JohnXX",
children: []
}]
}]
}]
You need to generate a new object with only the relevant parts.
This proposal works iterative for a single level and recursive for the children.
function getNodes(array, cb) {
return array.reduce(function iter(r, a) {
var children;
if (cb(a)) {
return r.concat(a);
}
if (Array.isArray(a.children)) {
children = a.children.reduce(iter, []);
}
if (children.length) {
return r.concat({ name: a.name, children: children });
}
return r;
}, []);
}
var data = [{ name: "Peter", children: [{ name: "John", children: [{ name: "Joseph", children: [] }] }, { name: "Shawn", children: [{ name: "Joseph", children: [] }] }] }, { name: "Carl", children: [{ name: "Sam", children: [{ name: "JohnXX", children: [] }] }] }];
console.log(getNodes(data, function (o) { return o.name.indexOf('John') !== -1; }));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Search for all paths to the value in JavaScript object

I have a complex JavaScript object given below.
An example object:
var object= {
"name": "tfifkhul",
"id": "262761",
"children": [
{
"name": "rthrth",
"id": 0,
"children": [
{
"name": "test",
"id": "262762",
"children": []
}
]
},
{
"name": "rthsrth",
"id": 0,
"children": [
{
"name": "test",
"id": "262762",
"children": []
}
]
},
{
"name": "rthrthhrth",
"id": 0,
"children": [
{
"name": "test",
"id": "262762",
"children": [
{
"name": "rtjrtj",
"id": 0,
"children": [
{
"name": "fwefwefwef",
"id": "262768",
"children": []
}
]
},
{
"name": "hsrtjrtdjrtj",
"id": 0,
"children": [
{
"name": "we4yhesrhy",
"id": "262764",
"children": []
}
]
},
{
"name": "lol",
"id": "262763",
"children": [
{
"name": "fwefwefwef",
"id": "262768",
"children": [
{
"name": "87ok78",
"id": "262765",
"children": [
{
"name": "78o78",
"id": 0,
"children": [
{
"name": "we4yhesrhy",
"id": "262764",
"children": [
{
"name": "test1",
"id": 0,
"children": [
{
"name": "",
"id": "262766",
"children": []
}
]
},
{
"name": "test2",
"id": 0,
"children": [
{
"name": "",
"id": "262766",
"children": []
}
]
}
]
}
]
},
{
"name": "7o78o76o8",
"id": 0,
"children": [
{
"name": "",
"id": "262766",
"children": []
}
]
},
{
"name": "ko",
"id": 0,
"children": [
{
"name": "",
"id": "262767",
"children": []
}
]
}
]
}
]
}
]
}
]
}
]
}
]
};
I need to create a function to search for all matching values for key "id" with given value.
So far I have created one recursive function:
function searchOccurances(theObject, value,path) {
var result = null;
if(theObject instanceof Array) {
for(var i = 0; i < theObject.length; i++) {
result = searchOccurances(theObject[i],value,path+","+i);
}
}
else
{
for(prop in theObject) {
if(prop == 'id') {
if(theObject[prop] == value) {
keyOccurances.push(path);
}
}
if((theObject[prop] instanceof Array) || (theObject[prop] instanceof Object))
{
if((theObject[prop].length!=undefined)&&(theObject[prop].length!=0))
{
result = searchOccurances(theObject[prop],value,path+","+prop);
}
}
}
}
return result;
}
keyOccurances=[];
searchOccurances(object,262762,'');
console.log(keyOccurances);
//Output
[",children,0,children,0", ",children,1,children,0", ",children,2,children,0"] -- correct
keyOccurances=[];
searchOccurances(object,262768,'');
console.log(keyOccurances);
//Output
[",children,1,children,0,children,1,children,0", ",children,1,children,0,children,2,children,0"] --wrong
The function returns array of comma separated paths of matched value but doesn't seems to be getting right results. For the first call with value '262762' gives corrects path list but for value '262768' gives incorrect path list.
Kindly help.
I'd suggest to provide a better test object. Would you really have so many children with 'id = 0' in a real use case? Would you have 2 children with the same ID at all? That makes things pretty hard to debug.
Below is an example function that should work as expected.
function search(object, value) {
var res = [], searchPath;
(searchPath = function(children, path) {
var n, newPath;
for(n in children) {
if(typeof children[n].id !== 'undefined' && parseInt(children[n].id, 10) === value) {
res.push(path);
}
newPath = path.slice();
newPath.push(children[n].id);
searchPath(children[n].children, newPath);
}
})([ object ], []);
return res;
}
console.log(search(object, 262762));
console.log(search(object, 262768));
Output:
[["262761", 0], ["262761", 0], ["262761", 0]]
[["262761", 0, "262762", 0], ["262761", 0, "262762", "262763"]]
The above code is not (yet) bullet-proof but hopefully is it short enough to be easily understandable.
If I understand your questions correctly, you're looking for all paths where a specific id is present. I'd recommend not reinventing the wheel here and using an existing library. We use object-scan for most of our data processing now. It's powerful once you wrap your head around it. Here is how you'd answer your question
// const objectScan = require('object-scan');
const findKeys = (haystack, id) => objectScan(['**'], {
joined: true,
filterFn: ({ value }) => value.id === id
})(haystack);
const object = { name: 'tfifkhul', id: '262761', children: [{ name: 'rthrth', id: 0, children: [{ name: 'test', id: '262762', children: [] }] }, { name: 'rthsrth', id: 0, children: [{ name: 'test', id: '262762', children: [] }] }, { name: 'rthrthhrth', id: 0, children: [{ name: 'test', id: '262762', children: [{ name: 'rtjrtj', id: 0, children: [{ name: 'fwefwefwef', id: '262768', children: [] }] }, { name: 'hsrtjrtdjrtj', id: 0, children: [{ name: 'we4yhesrhy', id: '262764', children: [] }] }, { name: 'lol', id: '262763', children: [{ name: 'fwefwefwef', id: '262768', children: [{ name: '87ok78', id: '262765', children: [{ name: '78o78', id: 0, children: [{ name: 'we4yhesrhy', id: '262764', children: [{ name: 'test1', id: 0, children: [{ name: '', id: '262766', children: [] }] }, { name: 'test2', id: 0, children: [{ name: '', id: '262766', children: [] }] }] }] }, { name: '7o78o76o8', id: 0, children: [{ name: '', id: '262766', children: [] }] }, { name: 'ko', id: 0, children: [{ name: '', id: '262767', children: [] }] }] }] }] }] }] }] };
console.log(findKeys(object, '262762'));
/* =>
[ 'children[2].children[0]',
'children[1].children[0]',
'children[0].children[0]' ]
*/
console.log(findKeys(object, '262768'));
/* =>
[ 'children[2].children[0].children[2].children[0]',
'children[2].children[0].children[0].children[0]' ]
*/
.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
Edit: The accepted answer didn't make much sense to me (based on the question), but here is how you could generate the same output
// const objectScan = require('object-scan');
const findIdPath = (haystack, id) => objectScan(['**'], {
reverse: false,
filterFn: ({ value, parents, context }) => {
if (value.id === id) {
context.push(parents.filter((p) => 'id' in p).map((p) => p.id).reverse());
}
}
})(haystack, []);
const object = { name: 'tfifkhul', id: '262761', children: [{ name: 'rthrth', id: 0, children: [{ name: 'test', id: '262762', children: [] }] }, { name: 'rthsrth', id: 0, children: [{ name: 'test', id: '262762', children: [] }] }, { name: 'rthrthhrth', id: 0, children: [{ name: 'test', id: '262762', children: [{ name: 'rtjrtj', id: 0, children: [{ name: 'fwefwefwef', id: '262768', children: [] }] }, { name: 'hsrtjrtdjrtj', id: 0, children: [{ name: 'we4yhesrhy', id: '262764', children: [] }] }, { name: 'lol', id: '262763', children: [{ name: 'fwefwefwef', id: '262768', children: [{ name: '87ok78', id: '262765', children: [{ name: '78o78', id: 0, children: [{ name: 'we4yhesrhy', id: '262764', children: [{ name: 'test1', id: 0, children: [{ name: '', id: '262766', children: [] }] }, { name: 'test2', id: 0, children: [{ name: '', id: '262766', children: [] }] }] }] }, { name: '7o78o76o8', id: 0, children: [{ name: '', id: '262766', children: [] }] }, { name: 'ko', id: 0, children: [{ name: '', id: '262767', children: [] }] }] }] }] }] }] }] };
console.log(findIdPath(object, '262762'));
// => [ [ '262761', 0 ], [ '262761', 0 ], [ '262761', 0 ] ]
console.log(findIdPath(object, '262768'));
// => [ [ '262761', 0, '262762', 0 ], [ '262761', 0, '262762', '262763' ] ]
.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

Categories

Resources