1

I have a case where I want to mark my 'posts' (like articles) with the country they belong to, while allowing to go a scope higher: example france < europe < world

This is how I structured my hierarchy: world.js

export default {
    world: {
        europe: {
            albania: 'albania',
            austria: 'austria',
            belgium: 'belgium',
            bulgaria: 'bulgaria',
            croatia: 'croatia',
            czech: 'czech',
            //...
            france: 'france'
    }
}

It is not necessary to have this structure. But what I want to achieve is that each 'post' I have would contain a location propoerty with a value like ['world', 'europe', 'france']. My pain is how to extract from the value 'france' its hierarchy ['world', 'europe', 'france'] without having to scan all the tree: I need kind of a reference to the property france to know to which 'context' it belongs to and navigate the tree in a child to parent way to obtain france (parent: europe (parent: world)) (not searching from the root where france might be in the structure)

Of course I can declare a verbose tree explicitly specifying the parent each time, but my question is about an elegant way of doing this

Zied Hamdi
  • 2,400
  • 1
  • 25
  • 40
  • I don't think there's a way. The DOM API (eg, window, document, document.body etc.) takes the approach of explicitly specifying parents for each level of the hierarchy. Only, the browser is doing that for you. You probably have to do the same. Objects themselves are fairly simple structures as they should be. – slebetman Sep 29 '22 at 09:11
  • Not possible. An object just holds some values, you don't actually have access to tree of nodes. So accessing `a.b.c` doesn't have any reference to what the path is, it just resolves to whatever value is there. You could try to scan the object programatically and build-up a map but it runs into a problem of duplicates like `{ USA: { cities: { london: "London" } }, UK: { cities: { london: "London"} } }` – VLAZ Sep 29 '22 at 09:11
  • 2
    Note that you don't have to do it manually. You can always write a recursive descent parser to walk the tree and add a `.parent` property to each level automatically. Even for the strings and numbers because everything's an object after all. – slebetman Sep 29 '22 at 09:13

0 Answers0