简体   繁体   中英

Find recursive (circular) id in array of Javascript objects

users= [
{Id: 1, parentId: 2},
{Id: 2, parentId: 3},
{Id: 3, parentId: 4},
{Id: 4, parentId: 1}
]

I have an array of objects. How can I get the cycling Id return true if array had.

1-2 2-3 3-4 4-1

case: finally, Id 1 parentId should not be 1 .

You need to traverse the "tree" and keep track of all nodes' Id that you encounter. If you encounter a given Id more than once, display an error.

 users = [ { Id: 1, parentId: 2 }, { Id: 2, parentId: 3 }, { Id: 3, parentId: 4 }, { Id: 4, parentId: 1 }, { Id: 34, parentId: 34 }, ] var ids = {} users.forEach(function (e) { if (e.Id == e.parentId) { console.log(`${e.Id} has same parent ${e.parentId}`) } if (ids[e.Id] || ids[e.parentId]) { console.log(`For id ${e.Id}, found duplicate parent ${e.parentId}`) } ids[e.Id] = true })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM