Javascript get full index of nested objectHow do JavaScript closures work?What is the most efficient way to deep clone an object in JavaScript?How do I remove a property from a JavaScript object?How do you get a timestamp in JavaScript?Which equals operator (== vs ===) should be used in JavaScript comparisons?How do I include a JavaScript file in another JavaScript file?Get the current URL with JavaScript?What does “use strict” do in JavaScript, and what is the reasoning behind it?How to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?
Is it important to consider tone, melody, and musical form while writing a song?
If I cast Expeditious Retreat, can I Dash as a bonus action on the same turn?
Example of a continuous function that don't have a continuous extension
How to test if a transaction is standard without spending real money?
LaTeX closing $ signs makes cursor jump
Can an x86 CPU running in real mode be considered to be basically an 8086 CPU?
can i play a electric guitar through a bass amp?
How do I create uniquely male characters?
Arthur Somervell: 1000 Exercises - Meaning of this notation
How does strength of boric acid solution increase in presence of salicylic acid?
How to format long polynomial?
Dragon forelimb placement
Can I ask the recruiters in my resume to put the reason why I am rejected?
Why are electrically insulating heatsinks so rare? Is it just cost?
How do we improve the relationship with a client software team that performs poorly and is becoming less collaborative?
Maximum likelihood parameters deviate from posterior distributions
What do you call a Matrix-like slowdown and camera movement effect?
The Two and the One
I’m planning on buying a laser printer but concerned about the life cycle of toner in the machine
The use of multiple foreign keys on same column in SQL Server
Do VLANs within a subnet need to have their own subnet for router on a stick?
Why doesn't Newton's third law mean a person bounces back to where they started when they hit the ground?
How can I prevent hyper evolved versions of regular creatures from wiping out their cousins?
Theorem, big Paralist and Amsart
Javascript get full index of nested object
How do JavaScript closures work?What is the most efficient way to deep clone an object in JavaScript?How do I remove a property from a JavaScript object?How do you get a timestamp in JavaScript?Which equals operator (== vs ===) should be used in JavaScript comparisons?How do I include a JavaScript file in another JavaScript file?Get the current URL with JavaScript?What does “use strict” do in JavaScript, and what is the reasoning behind it?How to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
const items = [
id: 'item1',
children: [
id: 'item1-1',
children: [
id: 'item1-1-1' ,
id: 'item1-1-2' ,
id: 'item1-1-3'
children: [
id: 'item1-1-3-1'
]
,
]
,
id: 'item1-2',
children: [
id: 'item1-2-1'
]
]
,
id: 'item2'
]
What I want to is like below,
function getFullDepthOfObject()
...
getFullIndexOfObject('item1') =====> return '1'
getFullIndexOfObject('item1-2') =====> return '1-2'
getFullIndexOfObject('item1-1-1') =====> return '1-1-1'
getFullIndexOfObject('item1-1-2') =====> return '1-1-2'
getFullIndexOfObject('item2') ===> return '2'
I have struggled with this too much time, But I couldn't make it. I think I should stack each of parent
index, But I don't know how to get its parent. Is there a way to do this?
Not parse of id
string. Each id has randomic string. The id like item1-2
is for easier demonstration.
I think my way is too verbose...
I tried like ...
// Get Full Index of item1-1
// First, get the target's depth.
var depth = 0;
function getDepthOfId(object, id)
var level;
if (object.id === id) return 1;
object.children && object.children.some(o => level = getDepthOfId(o, id));
return level && level + 1;
depth = getDepthOfId(items[0], 'item1-1');
console.log('depth === ', depth)
// Then, iterate recursively with length of depth.
var indexStacks = [];
function getNestedIndexOfId(obj, id, index)
if (obj.id === id)
indexStacks = [index, ...indexStacks]
return index;
if (obj.children)
depth++;
obj.children.map((child, i) =>
getNestedIndexOfId(child, id, i)
)
// I can get the inner index, but I can't get its parent id.
// I don't know how to this..
function getParentId(obj, id)
// ...?
var parentId;
return parentId;
for(var i=0; i<depth; i++)
getNestedIndexOfId('...')
// full path will be
indexStacks.join('-')
javascript
add a comment |
const items = [
id: 'item1',
children: [
id: 'item1-1',
children: [
id: 'item1-1-1' ,
id: 'item1-1-2' ,
id: 'item1-1-3'
children: [
id: 'item1-1-3-1'
]
,
]
,
id: 'item1-2',
children: [
id: 'item1-2-1'
]
]
,
id: 'item2'
]
What I want to is like below,
function getFullDepthOfObject()
...
getFullIndexOfObject('item1') =====> return '1'
getFullIndexOfObject('item1-2') =====> return '1-2'
getFullIndexOfObject('item1-1-1') =====> return '1-1-1'
getFullIndexOfObject('item1-1-2') =====> return '1-1-2'
getFullIndexOfObject('item2') ===> return '2'
I have struggled with this too much time, But I couldn't make it. I think I should stack each of parent
index, But I don't know how to get its parent. Is there a way to do this?
Not parse of id
string. Each id has randomic string. The id like item1-2
is for easier demonstration.
I think my way is too verbose...
I tried like ...
// Get Full Index of item1-1
// First, get the target's depth.
var depth = 0;
function getDepthOfId(object, id)
var level;
if (object.id === id) return 1;
object.children && object.children.some(o => level = getDepthOfId(o, id));
return level && level + 1;
depth = getDepthOfId(items[0], 'item1-1');
console.log('depth === ', depth)
// Then, iterate recursively with length of depth.
var indexStacks = [];
function getNestedIndexOfId(obj, id, index)
if (obj.id === id)
indexStacks = [index, ...indexStacks]
return index;
if (obj.children)
depth++;
obj.children.map((child, i) =>
getNestedIndexOfId(child, id, i)
)
// I can get the inner index, but I can't get its parent id.
// I don't know how to this..
function getParentId(obj, id)
// ...?
var parentId;
return parentId;
for(var i=0; i<depth; i++)
getNestedIndexOfId('...')
// full path will be
indexStacks.join('-')
javascript
1
Wouldn't this suffice?getFullIndexOfObject = index =>index.replace('item', '');
This looks like this is result you are looking for
– Miroslav Glamuzina
Mar 9 at 3:15
@MiroslavGlamuzina The item's id is for easier understood, my code has id withuuid
– Juntae
Mar 9 at 3:19
What does the real code look like? Because even if it is but it is still in the formatitem__UUID__
this would still be valid.
– Miroslav Glamuzina
Mar 9 at 3:30
add a comment |
const items = [
id: 'item1',
children: [
id: 'item1-1',
children: [
id: 'item1-1-1' ,
id: 'item1-1-2' ,
id: 'item1-1-3'
children: [
id: 'item1-1-3-1'
]
,
]
,
id: 'item1-2',
children: [
id: 'item1-2-1'
]
]
,
id: 'item2'
]
What I want to is like below,
function getFullDepthOfObject()
...
getFullIndexOfObject('item1') =====> return '1'
getFullIndexOfObject('item1-2') =====> return '1-2'
getFullIndexOfObject('item1-1-1') =====> return '1-1-1'
getFullIndexOfObject('item1-1-2') =====> return '1-1-2'
getFullIndexOfObject('item2') ===> return '2'
I have struggled with this too much time, But I couldn't make it. I think I should stack each of parent
index, But I don't know how to get its parent. Is there a way to do this?
Not parse of id
string. Each id has randomic string. The id like item1-2
is for easier demonstration.
I think my way is too verbose...
I tried like ...
// Get Full Index of item1-1
// First, get the target's depth.
var depth = 0;
function getDepthOfId(object, id)
var level;
if (object.id === id) return 1;
object.children && object.children.some(o => level = getDepthOfId(o, id));
return level && level + 1;
depth = getDepthOfId(items[0], 'item1-1');
console.log('depth === ', depth)
// Then, iterate recursively with length of depth.
var indexStacks = [];
function getNestedIndexOfId(obj, id, index)
if (obj.id === id)
indexStacks = [index, ...indexStacks]
return index;
if (obj.children)
depth++;
obj.children.map((child, i) =>
getNestedIndexOfId(child, id, i)
)
// I can get the inner index, but I can't get its parent id.
// I don't know how to this..
function getParentId(obj, id)
// ...?
var parentId;
return parentId;
for(var i=0; i<depth; i++)
getNestedIndexOfId('...')
// full path will be
indexStacks.join('-')
javascript
const items = [
id: 'item1',
children: [
id: 'item1-1',
children: [
id: 'item1-1-1' ,
id: 'item1-1-2' ,
id: 'item1-1-3'
children: [
id: 'item1-1-3-1'
]
,
]
,
id: 'item1-2',
children: [
id: 'item1-2-1'
]
]
,
id: 'item2'
]
What I want to is like below,
function getFullDepthOfObject()
...
getFullIndexOfObject('item1') =====> return '1'
getFullIndexOfObject('item1-2') =====> return '1-2'
getFullIndexOfObject('item1-1-1') =====> return '1-1-1'
getFullIndexOfObject('item1-1-2') =====> return '1-1-2'
getFullIndexOfObject('item2') ===> return '2'
I have struggled with this too much time, But I couldn't make it. I think I should stack each of parent
index, But I don't know how to get its parent. Is there a way to do this?
Not parse of id
string. Each id has randomic string. The id like item1-2
is for easier demonstration.
I think my way is too verbose...
I tried like ...
// Get Full Index of item1-1
// First, get the target's depth.
var depth = 0;
function getDepthOfId(object, id)
var level;
if (object.id === id) return 1;
object.children && object.children.some(o => level = getDepthOfId(o, id));
return level && level + 1;
depth = getDepthOfId(items[0], 'item1-1');
console.log('depth === ', depth)
// Then, iterate recursively with length of depth.
var indexStacks = [];
function getNestedIndexOfId(obj, id, index)
if (obj.id === id)
indexStacks = [index, ...indexStacks]
return index;
if (obj.children)
depth++;
obj.children.map((child, i) =>
getNestedIndexOfId(child, id, i)
)
// I can get the inner index, but I can't get its parent id.
// I don't know how to this..
function getParentId(obj, id)
// ...?
var parentId;
return parentId;
for(var i=0; i<depth; i++)
getNestedIndexOfId('...')
// full path will be
indexStacks.join('-')
javascript
javascript
edited Mar 9 at 4:29
Juntae
asked Mar 9 at 3:06
JuntaeJuntae
1,56342764
1,56342764
1
Wouldn't this suffice?getFullIndexOfObject = index =>index.replace('item', '');
This looks like this is result you are looking for
– Miroslav Glamuzina
Mar 9 at 3:15
@MiroslavGlamuzina The item's id is for easier understood, my code has id withuuid
– Juntae
Mar 9 at 3:19
What does the real code look like? Because even if it is but it is still in the formatitem__UUID__
this would still be valid.
– Miroslav Glamuzina
Mar 9 at 3:30
add a comment |
1
Wouldn't this suffice?getFullIndexOfObject = index =>index.replace('item', '');
This looks like this is result you are looking for
– Miroslav Glamuzina
Mar 9 at 3:15
@MiroslavGlamuzina The item's id is for easier understood, my code has id withuuid
– Juntae
Mar 9 at 3:19
What does the real code look like? Because even if it is but it is still in the formatitem__UUID__
this would still be valid.
– Miroslav Glamuzina
Mar 9 at 3:30
1
1
Wouldn't this suffice?
getFullIndexOfObject = index =>index.replace('item', '');
This looks like this is result you are looking for– Miroslav Glamuzina
Mar 9 at 3:15
Wouldn't this suffice?
getFullIndexOfObject = index =>index.replace('item', '');
This looks like this is result you are looking for– Miroslav Glamuzina
Mar 9 at 3:15
@MiroslavGlamuzina The item's id is for easier understood, my code has id with
uuid
– Juntae
Mar 9 at 3:19
@MiroslavGlamuzina The item's id is for easier understood, my code has id with
uuid
– Juntae
Mar 9 at 3:19
What does the real code look like? Because even if it is but it is still in the format
item__UUID__
this would still be valid.– Miroslav Glamuzina
Mar 9 at 3:30
What does the real code look like? Because even if it is but it is still in the format
item__UUID__
this would still be valid.– Miroslav Glamuzina
Mar 9 at 3:30
add a comment |
5 Answers
5
active
oldest
votes
const items = [
id: 'item1',
children: [
id: 'item1-1',
children: [
id: 'item1-1-1' ,
id: 'item1-1-2' ,
id: 'item1-1-3',
children: [
id: 'item1-1-3-1'
]
]
,
id: 'item1-2',
children: [
id: 'item1-2-1'
]
]
,
id: 'item2'
];
const searchIt = (node, search, path = '', position = 0) =>
if (node.id && node.id === search) return path !== '' ? `$path-$position` : position;
if (!node.children) return false
const index = node.children.findIndex((x) => x.id && x.id === search);
if (index >= 0)
return path !== '' ? `$path-$index + 1` : index + 1;
for (let i = 0; i < node.children.length; i++)
const result = searchIt(node.children[i], search, path !== '' ? `$path-$i+1` : i + 1, i);
if (result)
return result;
return false;
;
console.log(searchIt(children: items, 'item1-1'));
console.log(searchIt(children: items, 'item1-1-1'));
console.log(searchIt(children: items, 'item1-1-2'));
console.log(searchIt(children: items, 'item1-1-3'));
console.log(searchIt(children: items, 'item1-1-3-1'));
console.log(searchIt(children: items, 'item1-2-1'));
console.log(searchIt(children: items, 'item1-1-3-2'));
console.log(searchIt(children: items, 'item1-2-2'));
console.log(searchIt(children: items, 'item3'));
add a comment |
You could take an recursive and iterative approach. On found, the path is returned from the most inner object to the outer call of the function.
function getPath(array, id)
var result;
array.some((o, i) => );
return result;
const items = [ id: 'item1', children: [ id: 'item1-1', children: [ id: 'item1-1-1' , id: 'item1-1-2' , id: 'item1-1-3', children: [ id: 'item1-1-3-1'] ] , id: 'item1-2', children: [ id: 'item1-2-1' ] ] , id: 'item2' ];
console.log(getPath(items, 'item1')); // '1'
console.log(getPath(items, 'item1-2')); // '1-2'
console.log(getPath(items, 'item1-1-1')); // '1-1-1'
console.log(getPath(items, 'item1-1-2')); // '1-1-2'
console.log(getPath(items, 'item2')); // '2'
add a comment |
You can solve this problem using recursion. I have edited my code block and made it into a testable snippet. I had to fix an error in your data (missing comma or something don't remember).
const items = [
id: 'itemA',
children: [
id: 'item1-1',
children: [
id: 'item1-1-1' ,
id: 'item1-1-2' ,
id: 'item1-1-3', children: [ id: 'item1-1-3-1' ] ,
]
,
id: 'item1-2', children: [ id: 'item1-2-1' ] ,
],
,
id: 'item2'
];
const getItemLevel = (targetKey, item, depth = 0) =>
if (item.id === targetKey) return depth;
let foundLevel = null;
if (item.children)
item.children.forEach((child) =>
if (foundLevel) return;
foundLevel = getItemLevel(targetKey, child, depth +1);
)
return foundLevel;
console.log(getItemLevel('item1-1-1', id:'root', children: items ));
console.log(getItemLevel('item2', id:'root', children: items ));
console.log(getItemLevel('item1-1-3-1', id:'root', children: items ));
console.log(getItemLevel('keydoesnotexist', id:'root', children: items ));
I think this does return just depth of item, not a full path. Please read my question again...Thanks.
– Juntae
Mar 9 at 3:42
He's already using recursion, but needs to see the parent/child/grandchild relationship.
– lux
Mar 9 at 3:50
ok clearly I don't understand the question then because I read and re-read it, and I am still not getting it. Maybe because his ids are confusing? What's the output you want?
– JSager
Mar 9 at 3:51
So like, if you had an item that was id "A" that was the child of "B" that was the child of "C", do you want the output to be "C-B-A"?
– JSager
Mar 9 at 3:52
@JSager That items index. Each item is inside an array. So, if the itemitem1-1-1
will print1-1-1
From root to object, every index of its grandfather's index to its index. It's not actual index though,index + 1
actuaully.
– Juntae
Mar 9 at 4:14
|
show 4 more comments
a simple way:
const recursiveFind = (arr, id, res = indexes: [], found: false) =>
if (!Array.isArray(arr)) return res
const index = arr.findIndex(e => e.id === id)
if (index < 0)
for (let i = 0; i < arr.length; i++)
res.indexes.push(i+1)
const childIndexes = recursiveFind(arr[i].children, id, res)
if (childIndexes.found)
return childIndexes
else
res.found = true
res.indexes.push(index+1)
return res
recursiveFind(items, 'item1-1-2').indexes.join('-')
add a comment |
If it's ok to use Lodash+Deepdash, then:
let path;
_.eachDeep(items,(val,key,parent,context)=>
if(path) return false;
if(val.id=='item1-1-2')
path=context.path;
return false;
,tree:true,pathFormat:'array');
console.log(_(path).without('children').map(v=>parseInt(v)+1).join('-'));
Here is a codepen for this
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55073607%2fjavascript-get-full-index-of-nested-object%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
5 Answers
5
active
oldest
votes
5 Answers
5
active
oldest
votes
active
oldest
votes
active
oldest
votes
const items = [
id: 'item1',
children: [
id: 'item1-1',
children: [
id: 'item1-1-1' ,
id: 'item1-1-2' ,
id: 'item1-1-3',
children: [
id: 'item1-1-3-1'
]
]
,
id: 'item1-2',
children: [
id: 'item1-2-1'
]
]
,
id: 'item2'
];
const searchIt = (node, search, path = '', position = 0) =>
if (node.id && node.id === search) return path !== '' ? `$path-$position` : position;
if (!node.children) return false
const index = node.children.findIndex((x) => x.id && x.id === search);
if (index >= 0)
return path !== '' ? `$path-$index + 1` : index + 1;
for (let i = 0; i < node.children.length; i++)
const result = searchIt(node.children[i], search, path !== '' ? `$path-$i+1` : i + 1, i);
if (result)
return result;
return false;
;
console.log(searchIt(children: items, 'item1-1'));
console.log(searchIt(children: items, 'item1-1-1'));
console.log(searchIt(children: items, 'item1-1-2'));
console.log(searchIt(children: items, 'item1-1-3'));
console.log(searchIt(children: items, 'item1-1-3-1'));
console.log(searchIt(children: items, 'item1-2-1'));
console.log(searchIt(children: items, 'item1-1-3-2'));
console.log(searchIt(children: items, 'item1-2-2'));
console.log(searchIt(children: items, 'item3'));
add a comment |
const items = [
id: 'item1',
children: [
id: 'item1-1',
children: [
id: 'item1-1-1' ,
id: 'item1-1-2' ,
id: 'item1-1-3',
children: [
id: 'item1-1-3-1'
]
]
,
id: 'item1-2',
children: [
id: 'item1-2-1'
]
]
,
id: 'item2'
];
const searchIt = (node, search, path = '', position = 0) =>
if (node.id && node.id === search) return path !== '' ? `$path-$position` : position;
if (!node.children) return false
const index = node.children.findIndex((x) => x.id && x.id === search);
if (index >= 0)
return path !== '' ? `$path-$index + 1` : index + 1;
for (let i = 0; i < node.children.length; i++)
const result = searchIt(node.children[i], search, path !== '' ? `$path-$i+1` : i + 1, i);
if (result)
return result;
return false;
;
console.log(searchIt(children: items, 'item1-1'));
console.log(searchIt(children: items, 'item1-1-1'));
console.log(searchIt(children: items, 'item1-1-2'));
console.log(searchIt(children: items, 'item1-1-3'));
console.log(searchIt(children: items, 'item1-1-3-1'));
console.log(searchIt(children: items, 'item1-2-1'));
console.log(searchIt(children: items, 'item1-1-3-2'));
console.log(searchIt(children: items, 'item1-2-2'));
console.log(searchIt(children: items, 'item3'));
add a comment |
const items = [
id: 'item1',
children: [
id: 'item1-1',
children: [
id: 'item1-1-1' ,
id: 'item1-1-2' ,
id: 'item1-1-3',
children: [
id: 'item1-1-3-1'
]
]
,
id: 'item1-2',
children: [
id: 'item1-2-1'
]
]
,
id: 'item2'
];
const searchIt = (node, search, path = '', position = 0) =>
if (node.id && node.id === search) return path !== '' ? `$path-$position` : position;
if (!node.children) return false
const index = node.children.findIndex((x) => x.id && x.id === search);
if (index >= 0)
return path !== '' ? `$path-$index + 1` : index + 1;
for (let i = 0; i < node.children.length; i++)
const result = searchIt(node.children[i], search, path !== '' ? `$path-$i+1` : i + 1, i);
if (result)
return result;
return false;
;
console.log(searchIt(children: items, 'item1-1'));
console.log(searchIt(children: items, 'item1-1-1'));
console.log(searchIt(children: items, 'item1-1-2'));
console.log(searchIt(children: items, 'item1-1-3'));
console.log(searchIt(children: items, 'item1-1-3-1'));
console.log(searchIt(children: items, 'item1-2-1'));
console.log(searchIt(children: items, 'item1-1-3-2'));
console.log(searchIt(children: items, 'item1-2-2'));
console.log(searchIt(children: items, 'item3'));
const items = [
id: 'item1',
children: [
id: 'item1-1',
children: [
id: 'item1-1-1' ,
id: 'item1-1-2' ,
id: 'item1-1-3',
children: [
id: 'item1-1-3-1'
]
]
,
id: 'item1-2',
children: [
id: 'item1-2-1'
]
]
,
id: 'item2'
];
const searchIt = (node, search, path = '', position = 0) =>
if (node.id && node.id === search) return path !== '' ? `$path-$position` : position;
if (!node.children) return false
const index = node.children.findIndex((x) => x.id && x.id === search);
if (index >= 0)
return path !== '' ? `$path-$index + 1` : index + 1;
for (let i = 0; i < node.children.length; i++)
const result = searchIt(node.children[i], search, path !== '' ? `$path-$i+1` : i + 1, i);
if (result)
return result;
return false;
;
console.log(searchIt(children: items, 'item1-1'));
console.log(searchIt(children: items, 'item1-1-1'));
console.log(searchIt(children: items, 'item1-1-2'));
console.log(searchIt(children: items, 'item1-1-3'));
console.log(searchIt(children: items, 'item1-1-3-1'));
console.log(searchIt(children: items, 'item1-2-1'));
console.log(searchIt(children: items, 'item1-1-3-2'));
console.log(searchIt(children: items, 'item1-2-2'));
console.log(searchIt(children: items, 'item3'));
answered Mar 9 at 4:24
Thilina HasanthaThilina Hasantha
1315
1315
add a comment |
add a comment |
You could take an recursive and iterative approach. On found, the path is returned from the most inner object to the outer call of the function.
function getPath(array, id)
var result;
array.some((o, i) => );
return result;
const items = [ id: 'item1', children: [ id: 'item1-1', children: [ id: 'item1-1-1' , id: 'item1-1-2' , id: 'item1-1-3', children: [ id: 'item1-1-3-1'] ] , id: 'item1-2', children: [ id: 'item1-2-1' ] ] , id: 'item2' ];
console.log(getPath(items, 'item1')); // '1'
console.log(getPath(items, 'item1-2')); // '1-2'
console.log(getPath(items, 'item1-1-1')); // '1-1-1'
console.log(getPath(items, 'item1-1-2')); // '1-1-2'
console.log(getPath(items, 'item2')); // '2'
add a comment |
You could take an recursive and iterative approach. On found, the path is returned from the most inner object to the outer call of the function.
function getPath(array, id)
var result;
array.some((o, i) => );
return result;
const items = [ id: 'item1', children: [ id: 'item1-1', children: [ id: 'item1-1-1' , id: 'item1-1-2' , id: 'item1-1-3', children: [ id: 'item1-1-3-1'] ] , id: 'item1-2', children: [ id: 'item1-2-1' ] ] , id: 'item2' ];
console.log(getPath(items, 'item1')); // '1'
console.log(getPath(items, 'item1-2')); // '1-2'
console.log(getPath(items, 'item1-1-1')); // '1-1-1'
console.log(getPath(items, 'item1-1-2')); // '1-1-2'
console.log(getPath(items, 'item2')); // '2'
add a comment |
You could take an recursive and iterative approach. On found, the path is returned from the most inner object to the outer call of the function.
function getPath(array, id)
var result;
array.some((o, i) => );
return result;
const items = [ id: 'item1', children: [ id: 'item1-1', children: [ id: 'item1-1-1' , id: 'item1-1-2' , id: 'item1-1-3', children: [ id: 'item1-1-3-1'] ] , id: 'item1-2', children: [ id: 'item1-2-1' ] ] , id: 'item2' ];
console.log(getPath(items, 'item1')); // '1'
console.log(getPath(items, 'item1-2')); // '1-2'
console.log(getPath(items, 'item1-1-1')); // '1-1-1'
console.log(getPath(items, 'item1-1-2')); // '1-1-2'
console.log(getPath(items, 'item2')); // '2'
You could take an recursive and iterative approach. On found, the path is returned from the most inner object to the outer call of the function.
function getPath(array, id)
var result;
array.some((o, i) => );
return result;
const items = [ id: 'item1', children: [ id: 'item1-1', children: [ id: 'item1-1-1' , id: 'item1-1-2' , id: 'item1-1-3', children: [ id: 'item1-1-3-1'] ] , id: 'item1-2', children: [ id: 'item1-2-1' ] ] , id: 'item2' ];
console.log(getPath(items, 'item1')); // '1'
console.log(getPath(items, 'item1-2')); // '1-2'
console.log(getPath(items, 'item1-1-1')); // '1-1-1'
console.log(getPath(items, 'item1-1-2')); // '1-1-2'
console.log(getPath(items, 'item2')); // '2'
function getPath(array, id)
var result;
array.some((o, i) => );
return result;
const items = [ id: 'item1', children: [ id: 'item1-1', children: [ id: 'item1-1-1' , id: 'item1-1-2' , id: 'item1-1-3', children: [ id: 'item1-1-3-1'] ] , id: 'item1-2', children: [ id: 'item1-2-1' ] ] , id: 'item2' ];
console.log(getPath(items, 'item1')); // '1'
console.log(getPath(items, 'item1-2')); // '1-2'
console.log(getPath(items, 'item1-1-1')); // '1-1-1'
console.log(getPath(items, 'item1-1-2')); // '1-1-2'
console.log(getPath(items, 'item2')); // '2'
function getPath(array, id)
var result;
array.some((o, i) => );
return result;
const items = [ id: 'item1', children: [ id: 'item1-1', children: [ id: 'item1-1-1' , id: 'item1-1-2' , id: 'item1-1-3', children: [ id: 'item1-1-3-1'] ] , id: 'item1-2', children: [ id: 'item1-2-1' ] ] , id: 'item2' ];
console.log(getPath(items, 'item1')); // '1'
console.log(getPath(items, 'item1-2')); // '1-2'
console.log(getPath(items, 'item1-1-1')); // '1-1-1'
console.log(getPath(items, 'item1-1-2')); // '1-1-2'
console.log(getPath(items, 'item2')); // '2'
answered Mar 9 at 8:17
Nina ScholzNina Scholz
196k15108179
196k15108179
add a comment |
add a comment |
You can solve this problem using recursion. I have edited my code block and made it into a testable snippet. I had to fix an error in your data (missing comma or something don't remember).
const items = [
id: 'itemA',
children: [
id: 'item1-1',
children: [
id: 'item1-1-1' ,
id: 'item1-1-2' ,
id: 'item1-1-3', children: [ id: 'item1-1-3-1' ] ,
]
,
id: 'item1-2', children: [ id: 'item1-2-1' ] ,
],
,
id: 'item2'
];
const getItemLevel = (targetKey, item, depth = 0) =>
if (item.id === targetKey) return depth;
let foundLevel = null;
if (item.children)
item.children.forEach((child) =>
if (foundLevel) return;
foundLevel = getItemLevel(targetKey, child, depth +1);
)
return foundLevel;
console.log(getItemLevel('item1-1-1', id:'root', children: items ));
console.log(getItemLevel('item2', id:'root', children: items ));
console.log(getItemLevel('item1-1-3-1', id:'root', children: items ));
console.log(getItemLevel('keydoesnotexist', id:'root', children: items ));
I think this does return just depth of item, not a full path. Please read my question again...Thanks.
– Juntae
Mar 9 at 3:42
He's already using recursion, but needs to see the parent/child/grandchild relationship.
– lux
Mar 9 at 3:50
ok clearly I don't understand the question then because I read and re-read it, and I am still not getting it. Maybe because his ids are confusing? What's the output you want?
– JSager
Mar 9 at 3:51
So like, if you had an item that was id "A" that was the child of "B" that was the child of "C", do you want the output to be "C-B-A"?
– JSager
Mar 9 at 3:52
@JSager That items index. Each item is inside an array. So, if the itemitem1-1-1
will print1-1-1
From root to object, every index of its grandfather's index to its index. It's not actual index though,index + 1
actuaully.
– Juntae
Mar 9 at 4:14
|
show 4 more comments
You can solve this problem using recursion. I have edited my code block and made it into a testable snippet. I had to fix an error in your data (missing comma or something don't remember).
const items = [
id: 'itemA',
children: [
id: 'item1-1',
children: [
id: 'item1-1-1' ,
id: 'item1-1-2' ,
id: 'item1-1-3', children: [ id: 'item1-1-3-1' ] ,
]
,
id: 'item1-2', children: [ id: 'item1-2-1' ] ,
],
,
id: 'item2'
];
const getItemLevel = (targetKey, item, depth = 0) =>
if (item.id === targetKey) return depth;
let foundLevel = null;
if (item.children)
item.children.forEach((child) =>
if (foundLevel) return;
foundLevel = getItemLevel(targetKey, child, depth +1);
)
return foundLevel;
console.log(getItemLevel('item1-1-1', id:'root', children: items ));
console.log(getItemLevel('item2', id:'root', children: items ));
console.log(getItemLevel('item1-1-3-1', id:'root', children: items ));
console.log(getItemLevel('keydoesnotexist', id:'root', children: items ));
I think this does return just depth of item, not a full path. Please read my question again...Thanks.
– Juntae
Mar 9 at 3:42
He's already using recursion, but needs to see the parent/child/grandchild relationship.
– lux
Mar 9 at 3:50
ok clearly I don't understand the question then because I read and re-read it, and I am still not getting it. Maybe because his ids are confusing? What's the output you want?
– JSager
Mar 9 at 3:51
So like, if you had an item that was id "A" that was the child of "B" that was the child of "C", do you want the output to be "C-B-A"?
– JSager
Mar 9 at 3:52
@JSager That items index. Each item is inside an array. So, if the itemitem1-1-1
will print1-1-1
From root to object, every index of its grandfather's index to its index. It's not actual index though,index + 1
actuaully.
– Juntae
Mar 9 at 4:14
|
show 4 more comments
You can solve this problem using recursion. I have edited my code block and made it into a testable snippet. I had to fix an error in your data (missing comma or something don't remember).
const items = [
id: 'itemA',
children: [
id: 'item1-1',
children: [
id: 'item1-1-1' ,
id: 'item1-1-2' ,
id: 'item1-1-3', children: [ id: 'item1-1-3-1' ] ,
]
,
id: 'item1-2', children: [ id: 'item1-2-1' ] ,
],
,
id: 'item2'
];
const getItemLevel = (targetKey, item, depth = 0) =>
if (item.id === targetKey) return depth;
let foundLevel = null;
if (item.children)
item.children.forEach((child) =>
if (foundLevel) return;
foundLevel = getItemLevel(targetKey, child, depth +1);
)
return foundLevel;
console.log(getItemLevel('item1-1-1', id:'root', children: items ));
console.log(getItemLevel('item2', id:'root', children: items ));
console.log(getItemLevel('item1-1-3-1', id:'root', children: items ));
console.log(getItemLevel('keydoesnotexist', id:'root', children: items ));
You can solve this problem using recursion. I have edited my code block and made it into a testable snippet. I had to fix an error in your data (missing comma or something don't remember).
const items = [
id: 'itemA',
children: [
id: 'item1-1',
children: [
id: 'item1-1-1' ,
id: 'item1-1-2' ,
id: 'item1-1-3', children: [ id: 'item1-1-3-1' ] ,
]
,
id: 'item1-2', children: [ id: 'item1-2-1' ] ,
],
,
id: 'item2'
];
const getItemLevel = (targetKey, item, depth = 0) =>
if (item.id === targetKey) return depth;
let foundLevel = null;
if (item.children)
item.children.forEach((child) =>
if (foundLevel) return;
foundLevel = getItemLevel(targetKey, child, depth +1);
)
return foundLevel;
console.log(getItemLevel('item1-1-1', id:'root', children: items ));
console.log(getItemLevel('item2', id:'root', children: items ));
console.log(getItemLevel('item1-1-3-1', id:'root', children: items ));
console.log(getItemLevel('keydoesnotexist', id:'root', children: items ));
const items = [
id: 'itemA',
children: [
id: 'item1-1',
children: [
id: 'item1-1-1' ,
id: 'item1-1-2' ,
id: 'item1-1-3', children: [ id: 'item1-1-3-1' ] ,
]
,
id: 'item1-2', children: [ id: 'item1-2-1' ] ,
],
,
id: 'item2'
];
const getItemLevel = (targetKey, item, depth = 0) =>
if (item.id === targetKey) return depth;
let foundLevel = null;
if (item.children)
item.children.forEach((child) =>
if (foundLevel) return;
foundLevel = getItemLevel(targetKey, child, depth +1);
)
return foundLevel;
console.log(getItemLevel('item1-1-1', id:'root', children: items ));
console.log(getItemLevel('item2', id:'root', children: items ));
console.log(getItemLevel('item1-1-3-1', id:'root', children: items ));
console.log(getItemLevel('keydoesnotexist', id:'root', children: items ));
const items = [
id: 'itemA',
children: [
id: 'item1-1',
children: [
id: 'item1-1-1' ,
id: 'item1-1-2' ,
id: 'item1-1-3', children: [ id: 'item1-1-3-1' ] ,
]
,
id: 'item1-2', children: [ id: 'item1-2-1' ] ,
],
,
id: 'item2'
];
const getItemLevel = (targetKey, item, depth = 0) =>
if (item.id === targetKey) return depth;
let foundLevel = null;
if (item.children)
item.children.forEach((child) =>
if (foundLevel) return;
foundLevel = getItemLevel(targetKey, child, depth +1);
)
return foundLevel;
console.log(getItemLevel('item1-1-1', id:'root', children: items ));
console.log(getItemLevel('item2', id:'root', children: items ));
console.log(getItemLevel('item1-1-3-1', id:'root', children: items ));
console.log(getItemLevel('keydoesnotexist', id:'root', children: items ));
edited Mar 9 at 3:50
answered Mar 9 at 3:36
JSagerJSager
1,215714
1,215714
I think this does return just depth of item, not a full path. Please read my question again...Thanks.
– Juntae
Mar 9 at 3:42
He's already using recursion, but needs to see the parent/child/grandchild relationship.
– lux
Mar 9 at 3:50
ok clearly I don't understand the question then because I read and re-read it, and I am still not getting it. Maybe because his ids are confusing? What's the output you want?
– JSager
Mar 9 at 3:51
So like, if you had an item that was id "A" that was the child of "B" that was the child of "C", do you want the output to be "C-B-A"?
– JSager
Mar 9 at 3:52
@JSager That items index. Each item is inside an array. So, if the itemitem1-1-1
will print1-1-1
From root to object, every index of its grandfather's index to its index. It's not actual index though,index + 1
actuaully.
– Juntae
Mar 9 at 4:14
|
show 4 more comments
I think this does return just depth of item, not a full path. Please read my question again...Thanks.
– Juntae
Mar 9 at 3:42
He's already using recursion, but needs to see the parent/child/grandchild relationship.
– lux
Mar 9 at 3:50
ok clearly I don't understand the question then because I read and re-read it, and I am still not getting it. Maybe because his ids are confusing? What's the output you want?
– JSager
Mar 9 at 3:51
So like, if you had an item that was id "A" that was the child of "B" that was the child of "C", do you want the output to be "C-B-A"?
– JSager
Mar 9 at 3:52
@JSager That items index. Each item is inside an array. So, if the itemitem1-1-1
will print1-1-1
From root to object, every index of its grandfather's index to its index. It's not actual index though,index + 1
actuaully.
– Juntae
Mar 9 at 4:14
I think this does return just depth of item, not a full path. Please read my question again...Thanks.
– Juntae
Mar 9 at 3:42
I think this does return just depth of item, not a full path. Please read my question again...Thanks.
– Juntae
Mar 9 at 3:42
He's already using recursion, but needs to see the parent/child/grandchild relationship.
– lux
Mar 9 at 3:50
He's already using recursion, but needs to see the parent/child/grandchild relationship.
– lux
Mar 9 at 3:50
ok clearly I don't understand the question then because I read and re-read it, and I am still not getting it. Maybe because his ids are confusing? What's the output you want?
– JSager
Mar 9 at 3:51
ok clearly I don't understand the question then because I read and re-read it, and I am still not getting it. Maybe because his ids are confusing? What's the output you want?
– JSager
Mar 9 at 3:51
So like, if you had an item that was id "A" that was the child of "B" that was the child of "C", do you want the output to be "C-B-A"?
– JSager
Mar 9 at 3:52
So like, if you had an item that was id "A" that was the child of "B" that was the child of "C", do you want the output to be "C-B-A"?
– JSager
Mar 9 at 3:52
@JSager That items index. Each item is inside an array. So, if the item
item1-1-1
will print 1-1-1
From root to object, every index of its grandfather's index to its index. It's not actual index though, index + 1
actuaully.– Juntae
Mar 9 at 4:14
@JSager That items index. Each item is inside an array. So, if the item
item1-1-1
will print 1-1-1
From root to object, every index of its grandfather's index to its index. It's not actual index though, index + 1
actuaully.– Juntae
Mar 9 at 4:14
|
show 4 more comments
a simple way:
const recursiveFind = (arr, id, res = indexes: [], found: false) =>
if (!Array.isArray(arr)) return res
const index = arr.findIndex(e => e.id === id)
if (index < 0)
for (let i = 0; i < arr.length; i++)
res.indexes.push(i+1)
const childIndexes = recursiveFind(arr[i].children, id, res)
if (childIndexes.found)
return childIndexes
else
res.found = true
res.indexes.push(index+1)
return res
recursiveFind(items, 'item1-1-2').indexes.join('-')
add a comment |
a simple way:
const recursiveFind = (arr, id, res = indexes: [], found: false) =>
if (!Array.isArray(arr)) return res
const index = arr.findIndex(e => e.id === id)
if (index < 0)
for (let i = 0; i < arr.length; i++)
res.indexes.push(i+1)
const childIndexes = recursiveFind(arr[i].children, id, res)
if (childIndexes.found)
return childIndexes
else
res.found = true
res.indexes.push(index+1)
return res
recursiveFind(items, 'item1-1-2').indexes.join('-')
add a comment |
a simple way:
const recursiveFind = (arr, id, res = indexes: [], found: false) =>
if (!Array.isArray(arr)) return res
const index = arr.findIndex(e => e.id === id)
if (index < 0)
for (let i = 0; i < arr.length; i++)
res.indexes.push(i+1)
const childIndexes = recursiveFind(arr[i].children, id, res)
if (childIndexes.found)
return childIndexes
else
res.found = true
res.indexes.push(index+1)
return res
recursiveFind(items, 'item1-1-2').indexes.join('-')
a simple way:
const recursiveFind = (arr, id, res = indexes: [], found: false) =>
if (!Array.isArray(arr)) return res
const index = arr.findIndex(e => e.id === id)
if (index < 0)
for (let i = 0; i < arr.length; i++)
res.indexes.push(i+1)
const childIndexes = recursiveFind(arr[i].children, id, res)
if (childIndexes.found)
return childIndexes
else
res.found = true
res.indexes.push(index+1)
return res
recursiveFind(items, 'item1-1-2').indexes.join('-')
answered Mar 9 at 5:46
Andre FigueiredoAndre Figueiredo
7,65643362
7,65643362
add a comment |
add a comment |
If it's ok to use Lodash+Deepdash, then:
let path;
_.eachDeep(items,(val,key,parent,context)=>
if(path) return false;
if(val.id=='item1-1-2')
path=context.path;
return false;
,tree:true,pathFormat:'array');
console.log(_(path).without('children').map(v=>parseInt(v)+1).join('-'));
Here is a codepen for this
add a comment |
If it's ok to use Lodash+Deepdash, then:
let path;
_.eachDeep(items,(val,key,parent,context)=>
if(path) return false;
if(val.id=='item1-1-2')
path=context.path;
return false;
,tree:true,pathFormat:'array');
console.log(_(path).without('children').map(v=>parseInt(v)+1).join('-'));
Here is a codepen for this
add a comment |
If it's ok to use Lodash+Deepdash, then:
let path;
_.eachDeep(items,(val,key,parent,context)=>
if(path) return false;
if(val.id=='item1-1-2')
path=context.path;
return false;
,tree:true,pathFormat:'array');
console.log(_(path).without('children').map(v=>parseInt(v)+1).join('-'));
Here is a codepen for this
If it's ok to use Lodash+Deepdash, then:
let path;
_.eachDeep(items,(val,key,parent,context)=>
if(path) return false;
if(val.id=='item1-1-2')
path=context.path;
return false;
,tree:true,pathFormat:'array');
console.log(_(path).without('children').map(v=>parseInt(v)+1).join('-'));
Here is a codepen for this
answered Mar 11 at 21:24
Yuri GorYuri Gor
703416
703416
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55073607%2fjavascript-get-full-index-of-nested-object%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
Wouldn't this suffice?
getFullIndexOfObject = index =>index.replace('item', '');
This looks like this is result you are looking for– Miroslav Glamuzina
Mar 9 at 3:15
@MiroslavGlamuzina The item's id is for easier understood, my code has id with
uuid
– Juntae
Mar 9 at 3:19
What does the real code look like? Because even if it is but it is still in the format
item__UUID__
this would still be valid.– Miroslav Glamuzina
Mar 9 at 3:30