Question

I have been looking around for an answer to this but in vain.

I have a function which takes a table name as an argument. but this name can be an object.

loadDataFromServer = function(dataTable) {
 //data fetch code ...
datadump[dataTable] = response.getDataTable();
}
loadDataFromServer(['gchart']['data'])

The problem is I need to store the data in a variable datadump.gchart.data but the "gchart.data" part needs to be determined upon calling the function, not hard coded in it. my problem lies in the fact that datadump[['gchart']['data']] is not the same as datadump['gchart']['data'] (which is the same as datadump.gchart.data)

Does anybody here know a good way to do this? If the input was simply gchart_data, this would easily work, but the functions needs to able to handle it even if it needed to assign its data to blabla.blibli.bloebloe.stuff.

thanks in advance

Était-ce utile?

La solution

I think what you're looking for is this:

function (result) {
    datadump = {};
    datadump.gchart = {};
    datadump.gchart.data = result.gchart.data;

    // or

    datadump.gchart = {
        data: result.gchart.data
    };    
}

It's a little bit strange to it like this though. Do you absolutely need the gchart in your datadump?

Assigning to a random depth like blabla.blibli.bloebloe.stuff is not easily done.

You could flatten like: obj["blabla.blibli.bloebloe.stuff"] = {};

Or you could write a recursive merge, like:

var a, b, c;
a = { foo: { ipsum: "lorem" } };
b = { bar: {}, foo: { abc: "def" } };
c = recursive_merge(a, b); // { foo: { ipsum: "lorem", abc: "def" }, bar: {} };

Autres conseils

Have you function take a list of strings and iterate over them to recursively access (and, if necessary, create) properties of datadump. I use arguments here to use the list of arguments itself, but you could also just use a single argument that is an array of strings.

var loadDataFromServer = function() {
    var currObj = datadump;

    // iterate over the list of property names
    for(var i=0; i<arguments.length - 1; ++i) {
        var nextName = arguments[i];

        // if the object doesn't have this property, make it
        if(currObj[nextName] == undefined) {
            currObj[nextName] = {};
        }

        // use currObj's property as the new `currObj`
        currObj = currObj[nextName];
    }

    // load data into the final named property
    currObj[arguments[i]] = response.getDataTable();
}

loadDataFromServer('gchart', 'data');
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top