简体   繁体   中英

Extract keys from JavaScript object and use as variables

There is a method in PHP called extract which does exactly what I want to do here. Say I have an object that looks like this:

var data = {
    name: "Olly"
    age: 19
};

I want to run a method like extract(data) so that I can then access the properties in that object by just using name and age , instead of data.name and data.age .

I've done a bit of Googling and couldn't find anything.

You can use something like this:

function myTestFunction() {
    var data = {
        name: "Olly",
        age: 19,
    };
    for (var key in data) {
        this[key] = data[key];
    }
    alert(name +" is "+ age +"!");
}
myTestFunction();

(Try that here: http://jsfiddle.net/dHDxd/3/ )

Or even export them to global namespace, by using window[key] = data[key] . In any case, be very very careful with that, since the risk of clobbering the global namespace / override other stuff / etc. is very high.

Update: general-purpose extract()

function extract(data, where) {
    for (var key in data) {
        where[key] = data[key];
    }
}

function runTest() {
    var myData = { name: "Olly", age: 19, };
    extract(myData, this);
    alert(name +" is "+ age +"!");
}

runTest();

Here is more generic/multi-level/recurrent namespace extractor :)

function extract(rootObject, key) {
    var parts = key.split('.');
    var currentKey = parts.shift();
    return parts.length > 0 ? extract(rootObject[currentKey], parts.join('.')) : rootObject[currentKey];
}

var myObject = { a: { b: { c: 7 }}};
console.log(extract(myObject, 'a.b.c'));
console.log(extract(myObject, 'a'));

It seems like it is just like the "with" statement.

var data = {
    name: "Olly",
    age: 19,
};
with(data){
    alert(name +" is "+ age +"!"); //"Olly is age 19!"
    name = "Charlie";
    age = 28;
    alert(data.name +" is "+ data.age +"!"); //"Charlie is age 28!"
}
alert(data.name +" is "+ data.age +"!"); //"Charlie is age 28!"

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