arranging elements in to a hash array

2019-09-15 01:57发布

问题:

I am trying to break a javascript object in to small array so that I can easily access the innerlevel data whenever I needed.

I have used recursive function to access all nodes inside json, using the program

http://jsfiddle.net/SvMUN/1/

What I am trying to do here is that I want to store these in to a separate array so that I cn access it like

newArray.Microsoft= MSFT, Microsoft;
newArray.Intel Corp=(INTC, Fortune 500);
newArray.Japan=Japan
newArray.Bernanke=Bernanke;

Depth of each array are different, so the ones with single level can use the same name like I ve shown in the example Bernanke. Is it possible to do it this way?

回答1:

No, you reduce the Facets to a string named html - but you want an object.

function generateList(facets) {
    var map = {};
    (function recurse(arr) {
        var join = [];
        for (var i=0; i<arr.length; i++) {
            var current = arr[i].term; // every object must have one!
            current = current.replace(/ /g, "_");
            join.push(current);  // only on lowest level?
            if (current in arr[i]) 
                map[current] = recurse(arr[i][current]);
        }
        return join;
    })(facets)
    return map;
}

Demo on jsfiddle.net

To get the one-level-data, you could just add this else-statement after the if:

            else
                map[current] = [ current ]; // create Array manually

Altough I don't think the result (demo) makes much sense then.