最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

arrays - Extract keys from JavaScript object and use as variables - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question asked Jan 4, 2012 at 16:30 user1082754user1082754 3
  • Are you using a minifier or optimizer like Yahoo YUI or Google Closure? – Kris Krause Commented Jan 4, 2012 at 16:33
  • 1 I suppose Javascript's with statement is more closely similar to PHP's extract method. That being said, with is not very mon and I would not use it unless you truly understand how it works. See developer.mozilla/en/JavaScript/Reference/Statements/with – mjc Commented Jan 4, 2012 at 16:36
  • @KrisKrause No, I am not. Why do you ask? – user1082754 Commented Jan 4, 2012 at 16:36
Add a ment  | 

2 Answers 2

Reset to default 10

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/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'));
发布评论

评论列表(0)

  1. 暂无评论